Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to replace multiple substring at once and not sequentially?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading