如何在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 出阁宴祝福语姐姐简短