How do I remove a substring from the end of a string in Python?

I have the following code:

url = 'abcdc.com'
print(url.strip('.com'))

I expected: abcdc

I got: abcd

Now I do

url.rsplit('.com', 1)

Is there a better way?


You could do this:

url = 'abcdc.com'
if url.endswith('.com'):
    url = url[:-4]

Or using regular expressions:

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/77234.html

上一篇: 为什么我需要二进制模式下的'noeol'工作?

下一篇: 如何从Python中的字符串末尾删除子字符串?