加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 替换第一个出现在字符串中的所有匹配项

发布时间:2020-12-20 13:00:31 所属栏目:Python 来源:网络整理
导读:鉴于字符串: 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.stacke
鉴于字符串:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读