我有以下代码:

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

我以为是abcdc

我得到:abcd

现在我知道了

url.rsplit('.com', 1)

有没有更好的办法?


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


当前回答

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

其他回答

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

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

在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

因为这是一个非常受欢迎的问题,我添加了另一个现在可用的解决方案。在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。

一个更广泛的解决方案,增加替换后缀的可能性(你可以用空字符串替换),并设置替换的最大数量:

def replacesuffix(s,old,new='',limit=1):
    """
    String suffix replace; if the string ends with the suffix given by parameter `old`, such suffix is replaced with the string given by parameter `new`. The number of replacements is limited by parameter `limit`, unless `limit` is negative (meaning no limit).

    :param s: the input string
    :param old: the suffix to be replaced
    :param new: the replacement string. Default value the empty string (suffix is removed without replacement).
    :param limit: the maximum number of replacements allowed. Default value 1.
    :returns: the input string with a certain number (depending on parameter `limit`) of the rightmost occurrences of string given by parameter `old` replaced by string given by parameter `new`
    """
    if s[len(s)-len(old):] == old and limit != 0:
        return replacesuffix(s[:len(s)-len(old)],old,new,limit-1) + new
    else:
        return s

在您的情况下,给定默认参数,将获得所需的结果:

replacesuffix('abcdc.com','.com')
>>> 'abcdc'

一些更普遍的例子:

replacesuffix('whatever-qweqweqwe','qwe','N',2)
>>> 'whatever-qweNN'

replacesuffix('whatever-qweqweqwe','qwe','N',-1)
>>> 'whatever-NNN'

replacesuffix('12.53000','0',' ',-1)
>>> '12.53   '

因为似乎还没有人指出这一点:

url = "www.example.com"
new_url = url[:url.rfind(".")]

这应该比使用split()的方法更有效,因为不会创建新的列表对象,而且这种解决方案适用于带有几个点的字符串。