Pythonic way for inline replace string in one single line?

Viewed 86

Is there a more pythonic and elegant way to replace multiple times a string without doing this in a list?

I want need to do multiple replaces with a string. So.

s = 'Helloooo'
pattern = ["a",, "b", "c"]

new = [s.replace(p, "") for p in patterns)]

This gives a list and I do not want to waste more lines with a for loop...

What is possible with python like?

new = s.replace(p, "") for p in patterns
1 Answers

Do a re.sub(...) combined with a join of your patterns:

>>> import re
>>> s = 'abc'
>>> patterns = ['a', 'b', 'c']
>>> re.sub(rf'{"|".join(patterns)}', '', s)
''
>>> re.sub(rf'{"|".join(patterns)}', '', 'dabcd')
'dd'
Related