在Python列表中查找并替换多个字符串值

时间:2015-11-06 09:57:06

标签: python string list

非常类似于此question,除了我想将words中与error_list中的任何内容匹配的任何部分替换为''

error_list = ['[br]', '[ex]', 'Something']
words = ['how', 'much[ex]', 'is[br]', 'the', 'fish[br]', 'noSomething', 'really']

所需的输出是

 words = ['how', 'much', 'is', 'the', 'fish', 'no', 'really']

我徒劳的尝试是,

words = [w.replace(error_list , '') for w in word]

编辑:也许我也应该说我已经用循环完成了这个但是正在寻找一种更加pythonic的方式。

1 个答案:

答案 0 :(得分:1)

error_list = ['[br]', '[ex]', 'Something']
words = ['how', 'much[ex]', 'is[br]', 'the', 'fish[br]', 'noSomething', 'really']   

for j in error_list:
    for index, i in enumerate(words):
            if(j in i):
                    i1=i.replace(j,"")
                    words[index]= i1

<强>输出

['how', 'much', 'is', 'the', 'fish', 'no', 'really']

<强> See it in action