Replace all occurrences in string but the first one

  • A+
Category:Languages

Given the string:

X did something. X found it to be good, and so X went home.

I would like to replace all occurrences of X but the first one, with Y, such that the output string would look like:

X did something. Y found it to be good, and so Y went home.

I tried many regex patterns (based on https://vi.stackexchange.com/questions/10905/substitution-how-to-ignore-the-nth-first-occurrences-of-a-pattern) but failed to implement this with Python

 


str.partition splits a string into the part before a delimiter, the delimiter itself, and the part after, or the string and two empty strings if the delimiter doesn’t exist. What that comes down to is:

s = 'X did something. X found it to be good, and so X went home.' before, first, after = s.partition('X') result = before + first + after.replace('X', 'Y') 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: