How to replace multiple substring at once and not sequentially?

Question:

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.

Asked By: Zing

||

Answers:

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.'
Answered By: Chris

string.replace(‘dog’, ‘#temp’).replace(‘cat’, ‘dog’).replace(‘#temp’, ‘cat’)

Answered By: Chul Park

The simplest way is using count occurrences:

words = 'I have a dog but not a cat'
words = words.replace('cat', 'dog').replace('dog', 'cat', 1)
print(words)

# I have a cat but not a dog
Answered By: PublishPublication
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.