给定字符串:
X did something. X found it to be good, and so X went home.
我想用 Y 替换所有出现的 X
,但第一个出现,这样输出字符串将如下所示:
X did something. Y found it to be good, and so Y went home.
我尝试了很多正则表达式模式(基于 https://vi.stackexchange.com/questions/10905/substitution-how-to-ignore-the-nth-first-occurrences-of-a-pattern )但是没能用 Python 实现它
最佳答案
str.partition
将字符串拆分为分隔符之前的部分、分隔符本身和之后的部分,或者如果分隔符不存在,则拆分为字符串和两个空字符串。归结为:
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')
关于python - 替换字符串中除第一个以外的所有出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53239936/