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

问题描述

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

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'
,

您可以使用正则表达式来完成此操作,方法是从要删除的单词的交替中构建正则表达式,注意对字符串进行转义,以免其中的 [] 被处理作为特殊字符:

import re

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

regex = re.compile('|'.join(re.escape(r) for r in remove_list))

text = regex.sub('',text)
print(text)

输出:

Some texts  that I want to  replace

由于这可能会导致结果字符串中出现双空格,您可以使用 replace 删除它们,例如

text = regex.sub('',text).replace('  ',' ')

输出:

Some texts that I want to replace
,

我会用 void MyMethod() { SomeClass obj = new SomeClass(); SomeOtherMethod(obj.Value); ... GC.KeepAlive(obj); // or GC.KeepAlive(obj.Value); } 执行此操作以一次性删除所有子字符串:

re.sub

请注意,结果有两个空格,而不是每个部分都被删除的空格。如果您希望每次出现只留下一个空格,您可以使用稍微复杂的正则表达式:

>>> import re
>>> regex = '|'.join(map(re.escape,remove_list))
>>> re.sub(regex,'',text)
'Some texts  that I want to  replace'

还有其他方法可以编写类似的正则表达式;这将删除匹配之前的空格,但您也可以删除匹配之后的空格。您想要哪种行为取决于您的用例。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...