1

I have a list of strings like

l1 = ['John', 'London', '219980']

I want to remove elements of this list from given string say:

s1 = "This is John Clay. He is from London with 219980"

I know I can do it like

for l in l1:
    s1 = s1.replace(l, "")

But if the list is big it takes too much time.
Is there any other alternative solution for this?

Desired Output:

'This is  Clay. He is from  with '

EDIT:

The list is made in such a way that all the elements from the list are present in string(sentence).

Sociopath
  • 13,068
  • 19
  • 47
  • 75

2 Answers2

1

Using regular expressions and in particular re.sub, you can try:

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 '
user2390182
  • 72,016
  • 6
  • 67
  • 89
1

you simply use regex-or (|)

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

in case your l1 contains | you can escape it with r'\|' first

apple apple
  • 10,292
  • 2
  • 16
  • 36