我有以下代码:

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

我以为是abcdc

我得到:abcd

现在我知道了

url.rsplit('.com', 1)

有没有更好的办法?


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


当前回答

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

 url=url[:-4]

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

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

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

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

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

其他回答

我使用了内置的rstrip函数,如下所示:

string = "test.com"
suffix = ".com"
newstring = string.rstrip(suffix)
print(newstring)
test

在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=url.split(".")[0]

假设你想删除域名,不管它是什么(.com, .net等)。我建议找到。并从那一刻起移除一切。

url = 'abcdc.com'
dot_index = url.rfind('.')
url = url[:dot_index]

在这里,我使用rfind来解决像abcdc.com这样的url的问题,它应该被简化为abcdc.com的名称。

如果你也关心www.s,你应该明确地检查它们:

if url.startswith("www."):
   url = url.replace("www.","", 1)

replace中的1用于奇怪的边例,例如www.net.www.com

如果你的url比这更乱,看看人们用正则表达式回答的问题。

你可以使用split:

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