如何在Python中从字符串末尾删除子字符串?
如果要从字符串末尾删除子字符串,则应首先检查字符串是否以该子字符串结尾。如果是这样,则对字符串进行切片,仅保留不带子字符串的部分。例如,
def rchop(string, ending):
if string.endswith(ending):
return string[:-len(ending)]
return string
chopped_str = rchop('Hello world', 'orld')
print chopped_str这将给出输出:
Hello w
如果速度不重要,也可以在此处使用正则表达式。例如,
>>> import re
>>> re.sub('orld$', '', 'Hello world')
Hello w热门推荐
10 收围巾的祝福语简短
11 2026祝福语简短创意牛
12 简短正能量生日祝福语
13 朋友搬迁新房祝福语简短
14 生日哥哥祝福语简短独特
15 送离职同事简短祝福语
16 恭喜订婚的祝福语简短
17 圣诞简短祝福语给父母
18 今年节日祝福语简短