我有以下代码:

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

我以为是abcdc

我得到:abcd

现在我知道了

url.rsplit('.com', 1)

有没有更好的办法?


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


当前回答

使用replace和count

这可能看起来有点hack,但它确保你不使用startwith和if语句进行安全替换,使用replace的count参数你可以限制替换为一个:

mystring = "www.comwww.com"

前缀:

print(mystring.replace("www.","",1))

后缀(把前缀写反了).com变成了moc。

print(mystring[::-1].replace("moc.","",1)[::-1])

其他回答

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)

url[:-4]怎么样?

你可以使用split:

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

如果你只想剥离扩展:

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

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

在Python 3.9+上:

text.removesuffix(suffix)

在任何Python版本上:

def remove_suffix(text, suffix):
    return text[:-len(suffix)] if text.endswith(suffix) and len(suffix) != 0 else text

或者是一行语句:

remove_suffix = lambda text, suffix: text[:-len(suffix)] if text.endswith(suffix) and len(suffix) != 0 else text