Rabindra
Rabindra

Reputation: 401

Can string replace be written in list comprehension?

I have a text and a list.

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

I want to replace all elements from list in the string. So, I can do this:

for element in remove_list:
    text = text.replace(element, '')

I can also use regex. But can this be done in list comprehension or any single liner?

Upvotes: 2

Views: 736

Answers (3)

Nick
Nick

Reputation: 147166

You can do this with a regex by building a regex from an alternation of the words to remove, taking care to escape the strings so that the [ and ] in them don't get treated as special characters:

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)

Output:

Some texts  that I want to  replace

Since this may result in double spaces in the result string, you can remove them with replace e.g.

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

Output:

Some texts that I want to replace

Upvotes: 1

kaya3
kaya3

Reputation: 51053

I would do this with re.sub to remove all the substrings in one pass:

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

Note that the result has two spaces instead of one where each part was removed. If you want each occurrence to leave just one space, you can use a slightly more complicated regex:

>>> re.sub(r'\s*(' + regex + r')', '', text)
'Some texts that I want to replace'

There are other ways to write similar regexes; this one will remove the space preceding a match, but you could alternatively remove the space following a match instead. Which behaviour you want will depend on your use-case.

Upvotes: 1

user2390182
user2390182

Reputation: 73460

You can use functools.reduce:

from functools import reduce

text = reduce(lambda x, y: x.replace(y, ''), remove_list, text)
# 'Some texts  that I want to  replace'

Upvotes: 5

Related Questions