如何在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 生日广州男生祝福语简短