I want to replace multiple substring at once, for instance, in the following statement I want to replace dog with cat and cat with dog:
I have a dog but not a cat.
However, when I use sequential replace string.replace('dog', 'cat') and then string.replace('cat', 'dog'), I get the following.
I have a dog but not a dog.
I have a long list of replacements to be done at once so a nested replace with temp will not help.
>Solution :
One way using re.sub:
import re
string = "I have a dog but not a cat."
d = {"dog": "cat", "cat": "dog"}
new_string = re.sub("|".join(d), lambda x: d[x.group(0)], string)
Output:
'I have a cat but not a dog.'