我的清单如下:
alist = ['xx_comb', 'xx_combined', 'xxx_rrr', '123_comb']
我想将所有出现的'_comb'替换为'_eeee'....,而不是'xx_combined'。仅当单词以_comb结尾时,才应进行替换。
我尝试过
[sub.replace('_comb', '_eeee') for sub in alist if '_combined' not in sub)]
但是这不起作用。
仅当单词以_comb结尾时,才应进行替换。
这是.endswith
而不是in
的工作(是子字符串),也应该使用三进制if
而不是进行过滤的理解if
。那是:
alist = ['xx_comb', 'xx_combined', 'xxx_rrr', '123_comb']
result = [i.replace('_comb', '_eeee') if i.endswith('_comb') else i for i in alist]
print(result) # ['xx_eeee', 'xx_combined', 'xxx_rrr', '123_eeee']
条件的写入方式意味着任何带有_combined
的值都不在输出列表中。相反,您需要以_combined
不在值中为替换条件:
alist = ['xx_comb', 'xx_combined', 'xxx_rrr', '123_comb']
print([sub.replace('_comb', '_eeee') if '_combined' not in sub else sub for sub in alist])
输出:
['xx_eeee', 'xx_combined', 'xxx_rrr', '123_eeee']
不过根据您的问题的措辞,最好使用re.sub
将字符串末尾的_comb
替换为_eeee
:
import re
alist = ['xx_comb', 'xx_combined', 'xxx_rrr', '123_comb']
print([re.sub(r'_comb$', '_eeee', sub) for sub in alist])
输出:
['xx_eeee', 'xx_combined', 'xxx_rrr', '123_eeee']