2015-11-06 235 views
2

非常类似于此question,只是我想用''来替换与error_list中的任何内容匹配的words的任何部分。在Python列表中查找并替换多个字符串值列表

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

谷歌搜索你的问题的确切名称产生了一些好的信息(链接的目标是先打)。 – TigerhawkT3

+0

“Python替代多个字符串”的答案肯定会起作用,但它可能有点过于强大。最终,我将不得不创建一个与我的列表作为键,并用'“”作为值的字典。 – josh

回答

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

+0

这与我的原始方法有类似的循环,所以它应该很好地工作。 +1 – josh

+0

@josh我们可以跳过'if-case'!并欢迎任何新的方法.. – Ravichandra

相关问题