我有一个类似的字符串列表
l1 = ['John', 'London', '219980']
我想从给定的字符串中删除此列表的元素:
s1 = "This is John Clay. He is from London with 219980"
我知道我可以做到
for l in l1:
s1 = s1.replace(l, "")
但是,如果列表很大,则会花费太多时间。
还有其他替代解决方案吗?
所需的输出:
'This is Clay. He is from with '
编辑:
创建列表的方式是使列表中的所有元素都以字符串(句子)的形式出现。
答案 0 :(得分:1)
使用正则表达式,尤其是
re.sub
,您可以尝试:
import re
l1 = ['John', 'London', '219980']
s1 = "This is John Clay. He is from London with 219980"
p = '|'.join(l1) # pattern to replace
re.sub(p, '', s1)
# 'This is Clay. He is from with '
答案 1 :(得分:1)
您只需使用正则表达式或(|
)
import re
l1 = ['John', 'London', '219980']
s1 = "This is John Clay. He is from London with 219980"
re.sub('|'.join(l1),'',s1)
如果您的l1包含|
,则可以先使用r'\|'
对其进行转义