2015-11-06 59 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

相關問題