Home > other >  Replace specific substrings of a string with another substrings/word in python 3
Replace specific substrings of a string with another substrings/word in python 3

Time:12-06

I have a string as shown below

string1 = 'Goals|scored|Messi=hatrick Ronaldo=double and the match drawn Messi vs Ronaldo'

from the above, I would like to replace first 'Messi' with 'Leo' and first 'Ronaldo' with 'Cristiano'

The expected output is 'Goals|scored|Leo=hatrick Cristiano=double and the match drawn Messi vs Ronaldo'

CodePudding user response:

You need string.replace(), perhaps coupled with a dictionary of things you want to replace:


str = 'Goals|scored|Messi=hatrick Ronaldo=double and the match drawn Messi vs Ronaldo'

to_swap = {
   'Messi': 'Leo',
   'Ronaldo': 'Cristiano'
}

for old, new in to_swap.items():
    str = str.replace(old, new)

print('with replacements:', str)

CodePudding user response:

you can make it with the "replace" method in python replace()

  • Related