Home > OS >  In-line substring exchange in a Python string
In-line substring exchange in a Python string

Time:01-05

I have a string that says "Peter has a boat, but Steve has a car." . I need to change that to "Steve has a boat, but Peter has a car." The only way I can think of doing this is an ugly three-step replace() with a placeholder:

"Peter has a boat, but Steve has a car.".replace("Peter","placeholder").replace("Steve","Peter").replace("placeholder","Steve")

Is there a more concise and proper - and less awful and ugly - way to do this?

CodePudding user response:

Replace all occurrences of Steve with Peter and then replace first occurrence of Peter with Steve:

s = "Peter has a boat, but Steve has a car."
s.replace('Steve', 'Peter').replace('Peter', 'Steve', 1)
'Steve has a boat, but Peter has a car.'

CodePudding user response:

How about using re

import re
string = "Peter has a boat, but Steve has a car."
re.sub(r"(Peter|Steve)", lambda match: "Peter" if match.group()=="Steve" else "Steve", string)
  • Related