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

标签 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 的方式。

最佳答案

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

关于python - 在 Python 列表中查找并替换为多个字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33564015/

相关文章:

python - 从函数内部更新局部变量

python 访问 mysql 数据库无法加载库

c# - String、FormattableString、IFormattable 之间的区别

python - 测试字符串是否仅包含给定字符

python - 在 Python 中获取列表的值

python - 如何让 web2py 允许常规 http?

python - 在 python 中自定义 __instancecheck__

java - 扫描字符串直到找到字符串中的特定字符

python - 在参数列表中指定嵌套字典键

python - 将文本文件中的行追加到列表中时,会将整行设置为字符串。如何识别文本文件中的不同数据类型?