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: