-4

here problem is, I have the python string like "I love daddy and I love mom".in this string what I want is, "I love mom and I love daddy".

here is the python string

s='i love dad and  i love mom',
s1=s.replace('dad','mom'),
print(s1)

Here is the output is : i love mom and i love mom

But i need the output is : i love mom and i love dad

SHR
  • 7,940
  • 9
  • 38
  • 57
  • 1
    Could you provide more examples? You want to exchange words? – Dani Mesejo Nov 03 '18 at 12:20
  • just see the description and write your comment – BRAHMA REDDY Nov 03 '18 at 12:23
  • Please allow us to Google that for you: [python replace word in string site:stackoverflow.com](https://www.google.com/search?q=python+replace+word+in+string+site%3Astackoverflow.com) – jww Nov 03 '18 at 12:23
  • Possible duplicate of [Replacing specific words in a string (Python)](https://stackoverflow.com/questions/12538160/replacing-specific-words-in-a-string-python) – 0xInfection Nov 03 '18 at 12:26

1 Answers1

1

Create a dict with the replacements

replacements = {
    'daddy': 'mom',
    'mom': 'daddy',
}

Create a function to return the correct replacement from the dict based on a match object:

def find_replacement(m):
    return replacements[m.group(1)]

Then use re.sub

text = "I love daddy and I love mom"
regex = r'({})'.format(r'|'.join(re.escape(w) for w in replacements))
result = re.sub(regex, find_replacement, text)
print(result)
nosklo
  • 217,122
  • 57
  • 293
  • 297
  • String format doesn't do word replacement - it only replaces the formatting placeholders, like `{foo}`... – nosklo Nov 03 '18 at 12:29