首页 > 解决方案 > 替换字符串中的所有匹配项,但第一个匹配项

问题描述

给定字符串:

X 做了点什么。X 觉得很好,于是 X 就回家了。

我想X用 Y 替换除第一个之外的所有出现,这样输出字符串将如下所示:

X 做了点什么。Y 觉得很好,于是 Y 就回家了。

我尝试了许多正则表达式模式(基于https://vi.stackexchange.com/questions/10905/substitution-how-to-ignore-the-nth-first-occurrences-of-a-pattern)但未能实现这一点Python

标签: pythonregex

解决方案


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')

推荐阅读