SanthoshSolomon
SanthoshSolomon

Reputation: 1402

Replacing multiple values in a string - Python

I have a string say 'I have a string' and a list ['I', 'string']. if i have to remove all the elements in the list from the given string, a proper for loop is working fine. But when I try the same with a list comprehension, it is not working as expected but returns a list.

my_string = 'I have a string'
replace_list = ['I', 'string']
for ele in replace_list:
    my_string = my_string.replace(ele, '')
# results --> ' have a '
[my_string.replace(ele, '') for ele in replace_list]
# results --> [' have a string', 'I have a ']

Is there any way to do it more efficiently?

Upvotes: 0

Views: 106

Answers (1)

gmds
gmds

Reputation: 19885

Use a regex:

import re

to_replace = ['I', 'string']
regex = re.compile('|'.join(to_replace))

re.sub(regex, '', my_string)

Output:

' have a '

Alternatively, you can use reduce:

from functools import reduce

def bound_replace(string, old):
    return string.replace(old, '')

reduce(bound_replace, to_replace, my_string)

Output:

' have a '

Upvotes: 3

Related Questions