我有以下代码:
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中工作?对于第一次尝试的具体解释。
当前回答
在我的情况下,我需要引发一个异常,所以我做了:
class UnableToStripEnd(Exception):
"""A Exception type to indicate that the suffix cannot be removed from the text."""
@staticmethod
def get_exception(text, suffix):
return UnableToStripEnd("Could not find suffix ({0}) on text: {1}."
.format(suffix, text))
def strip_end(text, suffix):
"""Removes the end of a string. Otherwise fails."""
if not text.endswith(suffix):
raise UnableToStripEnd.get_exception(text, suffix)
return text[:len(text)-len(suffix)]
其他回答
在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
使用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])
你可以使用split:
'abccomputer.com'.split('.com',1)[0]
# 'abccomputer'
如果你知道是分机,那么
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'