gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 12:13:36 25 4
gpt4 key购买 nike

给定字符串:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com