我有以下代码:

url = 'abcdc.com'
print(url.strip('.com'))

我以为是abcdc

我得到:abcd

现在我知道了

url.rsplit('.com', 1)

有没有更好的办法?


参见.strip/.rstrip/。lstrip字符串方法在Python中工作?对于第一次尝试的具体解释。


当前回答

对于url(通过给定的例子,它似乎是主题的一部分),可以这样做:

import os
url = 'http://www.stackoverflow.com'
name,ext = os.path.splitext(url)
print (name, ext)

#Or:
ext = '.'+url.split('.')[-1]
name = url[:-len(ext)]
print (name, ext)

两者都会输出: (“http://www.stackoverflow”,“。com”)

这也可以与str.endswith(后缀)相结合,如果你只需要分割“。com”,或任何特定的东西。

其他回答

这里,我有一个最简单的代码。

url=url.split(".")[0]

从Python 3.9开始,你可以使用removesuffix:

'abcdc.com'.removesuffix('.com')
# 'abcdc'

在我的情况下,我需要引发一个异常,所以我做了:

class UnableToStripEnd(Exception):
    """A Exception type to indicate that the suffix cannot be removed from the text."""

    @staticmethod
    def get_exception(text, suffix):
        return UnableToStripEnd("Could not find suffix ({0}) on text: {1}."
                                .format(suffix, text))


def strip_end(text, suffix):
    """Removes the end of a string. Otherwise fails."""
    if not text.endswith(suffix):
        raise UnableToStripEnd.get_exception(text, suffix)
    return text[:len(text)-len(suffix)]

对于url(通过给定的例子,它似乎是主题的一部分),可以这样做:

import os
url = 'http://www.stackoverflow.com'
name,ext = os.path.splitext(url)
print (name, ext)

#Or:
ext = '.'+url.split('.')[-1]
name = url[:-len(ext)]
print (name, ext)

两者都会输出: (“http://www.stackoverflow”,“。com”)

这也可以与str.endswith(后缀)相结合,如果你只需要分割“。com”,或任何特定的东西。

如果你确定字符串只出现在末尾,那么最简单的方法是使用'replace':

url = 'abcdc.com'
print(url.replace('.com',''))