Home > Software engineering >  How to replace multiple substring at once and not sequentially?
How to replace multiple substring at once and not sequentially?

Time:10-05

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.

CodePudding user response:

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.'

CodePudding user response:

string.replace('dog', '#temp').replace('cat', 'dog').replace('#temp', 'cat')

CodePudding user response:

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
  • Related