【发布时间】:2021-11-19 16:37:11
【问题描述】:
我有一堆替换函数来修改我拥有的字符串列表。最初,我已经写出了我想要替换的字符串的每个列表理解。
ls = ['sentence with string a', 'sentence with string d and string a',
'sentence with string d', 'sentence with string b and string b again',
'sentence with string c', 'sentence with string c and string d']
ls = [x.replace('string a' , '') for x in ls]
ls = [x.replace('string b' , '') for x in ls]
ls = [x.replace('string c' , '') for x in ls]
ls = [x.replace('string d' , '') for x in ls]
ls = ['sentence with', 'sentence with and',
'sentence with', 'sentence with and again',
'sentence with', 'sentence with and']
但是,由于我要替换的字符串可能会更改,因此我想使用列表来执行所有替换功能。当我尝试 for 循环时,这最终会从字符串中间删除字符,并且不会像以前那样给我列表。
words = ['string a', 'string b', 'string c', 'string d']
for txt in words:
ls = [x.replace(txt, "") for x in ls]
如何使用字符串列表来获得相同的结果?
【问题讨论】:
-
从混乱的语法突出显示中可以看出,您的代码似乎没有意义。
-
您在
words = [末尾缺少] -
除了那个错字,它看起来应该可以工作。
-
您在第一个代码块中缺少一堆
'字符。x.replace('string a' , ')应该是x.replace('string a' , '') -
为什么不使用推导式?