python - 替换字符串中除第一个以外的所有出现

标签 python regex

给定字符串:

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/

相关文章:

python - 将多个NetCDF文件组合成timeseries多维数组python

python - 如何序列化 sympy lambdified 函数?

javascript - 试图找到漂亮网址的正则表达式

python - 将 sympy 矩阵转换为两种形式 (sympy.diffgeom)

python - Django.core.exceptions.ImproperlyConfigured : AUTH_USER_MODEL refers to model %s that has not been installed

python - Tkinter 函数 "root.after()"不运行指定的函数

java - 用正则表达式统计单词 "\S+"

c# - 获取字符串中两个字符串之间的字符串

javascript - 在查找和替换中使用正则表达式提取除模式/字符串之外的所有内容

java regex - 捕获重复组