我有以下代码:

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

我以为是abcdc

我得到:abcd

现在我知道了

url.rsplit('.com', 1)

有没有更好的办法?


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


当前回答

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

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

其他回答

你可以使用split:

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

在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

这取决于你对url的了解程度以及你想要做什么。如果你知道它总是以“。com”(或“。net”或“。org”)结尾,那么

 url=url[:-4]

是最快的解决办法。如果它是一个更通用的url,那么你可能会更好地查看python附带的urlparse库。

另一方面,如果你只是想在期末考试后删除所有内容。'在一个字符串中

url.rsplit('.',1)[0]

将工作。或者如果你想把所有的东西都放在第一。那就试试

url.split('.',1)[0]

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

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

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

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

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