python - 替换字符串中的所有匹配项,但第一个匹配项
问题描述
给定字符串:
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
解决方案
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')
推荐阅读
- xcode - XCode,泄漏仪器不工作,“尝试捕获分配数据时发生错误”
- javascript - 使用 Firebase Cloud Functions 访问 Firebase Storage 中的文件时出现问题,文件返回“[object Object]”
- python - 我如何比较时区和日期时间的实例
- kubernetes - 使用 config-dir 运行领事代理导致未找到异常
- emacs - orgmode 日志抽屉总时间未按预期计算
- scala - Scala Spark 通过成对的 RDD 元素映射
- php - wordpress 搜索分页在哪里
- javascript - 通过JS从历史中删除多个项目
- javascript - 视图可以在 MVC 模式中进行 AJAX 调用吗?
- angular - 使用 Angular 一起调用带有 @RequestParam 和 @RequestBody 的 RESTful Web 服务