如何在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 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短