我有以下代码:
url = 'abcdc.com'
print(url.strip('.com'))
我以为是abcdc
我得到:abcd
现在我知道了
url.rsplit('.com', 1)
有没有更好的办法?
参见.strip/.rstrip/。lstrip字符串方法在Python中工作?对于第一次尝试的具体解释。
我有以下代码:
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'
其他回答
如果你知道是分机,那么
url = 'abcdc.com'
...
url.rsplit('.', 1)[0] # split at '.', starting from the right, maximum 1 split
这同样适用于abcdc.com或www.abcdc.com或abcdc。[任何东西]并且更具有可扩展性。
这是正则表达式的完美用法:
>>> import re
>>> re.match(r"(.*)\.com", "hello.com").group(1)
'hello'
你可以使用split:
'abccomputer.com'.split('.com',1)[0]
# 'abccomputer'
因为似乎还没有人指出这一点:
url = "www.example.com"
new_url = url[:url.rfind(".")]
这应该比使用split()的方法更有效,因为不会创建新的列表对象,而且这种解决方案适用于带有几个点的字符串。
从Python 3.9开始,你可以使用removesuffix:
'abcdc.com'.removesuffix('.com')
# 'abcdc'