我有一个文本和一个列表。
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/