0

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?

1 Answer 1

3

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 '
Sign up to request clarification or add additional context in comments.

5 Comments

alternatively you can use a lambda to replace your function reduce(lambda string,old: string.replace(old, ''),to_replace,my_string)
@AJS I prefer to avoid lambda functions where possible, because I find Python's syntax in that regard quite clunky.
yea its a matter of preference.
So there is no any function like str_replace_all() in R?
@SmashGuy I don't know R, but there is no inbuilt function to replace multiple arbitrary substrings. There's translate for single characters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.