具有子字符串替换功能的列表理解无法正常工作

问题描述 投票:0回答:1

我的清单如下:

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)]

但是这不起作用。

python list-comprehension
1个回答
2
投票

仅当单词以_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']

1
投票

条件的写入方式意味着任何带有_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']
© www.soinside.com 2019 - 2024. All rights reserved.