我有以下代码:
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中工作?对于第一次尝试的具体解释。
当前回答
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'
其他回答
从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。[任何东西]并且更具有可扩展性。
这里,我有一个最简单的代码。
url=url.split(".")[0]
这是正则表达式的完美用法:
>>> import re
>>> re.match(r"(.*)\.com", "hello.com").group(1)
'hello'
你可以使用split:
'abccomputer.com'.split('.com',1)[0]
# 'abccomputer'