我有以下代码:

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

我以为是abcdc

我得到:abcd

现在我知道了

url.rsplit('.com', 1)

有没有更好的办法?


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


当前回答

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

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

其他回答

import re

def rm_suffix(url = 'abcdc.com', suffix='\.com'):
    return(re.sub(suffix+'$', '', url))

我想重复一下这个答案,作为最具表现力的回答。当然,以下操作会占用更少的CPU时间:

def rm_dotcom(url = 'abcdc.com'):
    return(url[:-4] if url.endswith('.com') else url)

但是,如果CPU是瓶颈,为什么要用Python编写呢?

CPU什么时候会成为瓶颈?在驾驶方面,可能是这样。

使用正则表达式的优点是代码可重用性。如果你接下来想要移除。Me ',只有三个字?

同样的代码可以做到这一点:

>>> rm_sub('abcdc.me','.me')
'abcdc'

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

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

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

如果你知道是分机,那么

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

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

你可以使用split:

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

使用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])