我有以下代码:
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
>>> re.match(r"(.*)\.com", "hello.com").group(1)
'hello'
其他回答
如果你确定字符串只出现在末尾,那么最简单的方法是使用'replace':
url = 'abcdc.com'
print(url.replace('.com',''))
这里,我有一个最简单的代码。
url=url.split(".")[0]
Strip并不是指“删除这个子字符串”。x.strip(y)将y视为一个字符集,并从x的两端剥离该字符集中的任何字符。
在Python 3.9及更新版本中,您可以使用removeprefix和removesuffix方法从字符串的任意一侧删除整个子字符串:
url = 'abcdc.com'
url.removesuffix('.com') # Returns 'abcdc'
url.removeprefix('abcdc.') # Returns 'com'
相关的Python增强提案是PEP-616。
在Python 3.8及以上版本中,你可以使用endswith和slicing:
url = 'abcdc.com'
if url.endswith('.com'):
url = url[:-4]
或者正则表达式:
import re
url = 'abcdc.com'
url = re.sub('\.com$', '', url)
在我的情况下,我需要引发一个异常,所以我做了:
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)]
def strip_end(text, suffix):
if suffix and text.endswith(suffix):
return text[:-len(suffix)]
return text