如何从字符串中删除列表中的所有元素?

2024-04-29 01:58:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字符串列表,比如

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 '

编辑:

列表的制作方式使列表中的所有元素都以字符串(句子)的形式出现。你知道吗


Tags: 字符串infrom元素l1列表foris
2条回答

只需使用regex或(|

import re
l1 = ['John', 'London', '219980']
s1 = "This is John Clay. He is from London with 219980"
re.sub('|'.join(l1),'',s1)

如果l1包含|,可以先用r'\|'对其进行转义

使用正则表达式,尤其是 ^{},您可以尝试:

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 '

相关问题 更多 >