如何从Python中的字符串末尾删除子字符串?
我有以下代码:
url = 'abcdc.com'
print(url.strip('.com'))
我期望: abcdc
我得到了: abcd
现在我知道了
url.rsplit('.com', 1)
有没有更好的办法?
你可以这样做:
url = 'abcdc.com'
if url.endswith('.com'):
url = url[:-4]
或者使用正则表达式:
import re
url = 'abcdc.com'
url = re.sub('.com$', '', url)
如果你确定字符串只出现在最后,那么最简单的方法就是使用'替换':
url = 'abcdc.com'
print url.replace('.com','')
def strip_end(text, suffix):
if not text.endswith(suffix):
return text
return text[:len(text)-len(suffix)]
链接地址: http://www.djcxy.com/p/77233.html
上一篇: How do I remove a substring from the end of a string in Python?