python - 字符串替换可以写在列表理解中吗?

标签 python python-3.x list-comprehension

我有一个文本和一个列表。

text = "Some texts [remove me] that I want to [and remove me] replace"
remove_list = ["[remove me]", "[and remove me]"]

我想替换字符串中列表中的所有元素。所以,我可以这样做:

for element in remove_list:
    text = text.replace(element, '')

我也可以使用正则表达式。 但这可以在列表推导式或任何单行中完成吗?

最佳答案

您可以使用 functools.reduce :

from functools import reduce

text = reduce(lambda x, y: x.replace(y, ''), remove_list, text)
# 'Some texts  that I want to  replace'

关于python - 字符串替换可以写在列表理解中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67054417/

相关文章:

Python for 和 if 在一行

python - Matplotlib:将原点移动到左上角

python - 转换为 float 时出现列错误

c++ - 如何生成像列表理解这样的 vector

python - 如何在matplotlib绘图的xlabel中打印10K,20K......1M

python - Python类之间如何通信?

python - 使用先前列表的值更改创建一个新列表

python - str.startswith 带有要测试的字符串列表

python csv.read 在第二次迭代时失败

python - 如何解决绘图变量尺寸不匹配的错误?