我有以下代码:

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

我以为是abcdc

我得到:abcd

现在我知道了

url.rsplit('.com', 1)

有没有更好的办法?


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


当前回答

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

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)]

其他回答

Strip并不是指“删除这个子字符串”。x.strip(y)将y视为一个字符集,并从x的两端剥离该字符集中的任何字符。

在Python 3.9及更新版本中,您可以使用removeprefix和removesuffix方法从字符串的任意一侧删除整个子字符串:

url = 'abcdc.com'
url.removesuffix('.com')    # Returns 'abcdc'
url.removeprefix('abcdc.')  # Returns 'com'

相关的Python增强提案是PEP-616。

在Python 3.8及以上版本中,你可以使用endswith和slicing:

url = 'abcdc.com'
if url.endswith('.com'):
    url = url[:-4]

或者正则表达式:

import re
url = 'abcdc.com'
url = re.sub('\.com$', '', url)

你可以使用split:

'abccomputer.com'.split('.com',1)[0]
# 'abccomputer'

对于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”,或任何特定的东西。

如果你只想剥离扩展:

'.'.join('abcdc.com'.split('.')[:-1])
# 'abcdc'

它适用于任何扩展名,与潜在的其他点存在的文件名以及。它只是将字符串拆分为一个点列表,并在没有最后一个元素的情况下将其连接起来。

这个方法有一个严重的缺陷,分区没有锚定到url的末尾,可能会返回虚假的结果。例如,URL“www.comcast.net”的结果是“www”(不正确),而不是预期的“www.comcast.net”。因此,这种解决方案是邪恶的。除非你知道你在做什么,否则不要使用它!

url.rpartition('.com')[0]

这是相当容易键入的,也正确地返回原始字符串(没有错误)时,后缀'.com'从url中丢失。