我有以下代码:

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

我以为是abcdc

我得到:abcd

现在我知道了

url.rsplit('.com', 1)

有没有更好的办法?


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


当前回答

如果你知道是分机,那么

url = 'abcdc.com'
...
url.rsplit('.', 1)[0]  # split at '.', starting from the right, maximum 1 split

这同样适用于abcdc.com或www.abcdc.com或abcdc。[任何东西]并且更具有可扩展性。

其他回答

因为这是一个非常受欢迎的问题,我添加了另一个现在可用的解决方案。在python 3.9 (https://docs.python.org/3.9/whatsnew/3.9.html)中,函数removesuffix()将被添加(和removeprefix()),这个函数正是这里所质疑的。

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

输出:

'abcdc'

PEP 616 (https://www.python.org/dev/peps/pep-0616/)显示了它的行为(它不是真正的实现):

def removeprefix(self: str, prefix: str, /) -> str:
    if self.startswith(prefix):
        return self[len(prefix):]
    else:
        return self[:]

与自我实现的解决方案相比,它有什么好处:

不那么脆弱: 代码将不依赖于用户来计算文字的长度。 更多的性能: 该代码不需要调用Python内置的len函数,也不需要调用更昂贵的str.replace()方法。 更具描述性的: 与传统的字符串切片方法相比,这些方法为代码可读性提供了更高级别的API。

在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 = 'abcdc.com'
...
url.rsplit('.', 1)[0]  # split at '.', starting from the right, maximum 1 split

这同样适用于abcdc.com或www.abcdc.com或abcdc。[任何东西]并且更具有可扩展性。

def strip_end(text, suffix):
    if suffix and text.endswith(suffix):
        return text[:-len(suffix)]
    return text

假设你想删除域名,不管它是什么(.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比这更乱,看看人们用正则表达式回答的问题。