python - 替换 Python 中特定出现的字符串

标签 python string substitution

假设我有

examplestring='hello abcde hello xyz hello goodbye'.

我想将第二次出现的“hello”替换为“bye”,而不替换所有出现的“hello”。

我该怎么做?

最佳答案

你可以拆分然后加入:

In [1]: s = 'hello abcde hello xyz hello goodbye'

In [2]: words = s.split('hello')

In [3]: 'hello'.join(words[:2]) + 'bye' + 'hello'.join(words[2:])
Out[3]: 'hello abcde bye xyz hello goodbye'

关于python - 替换 Python 中特定出现的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31602553/

相关文章:

python - 将函数的输出传递给 django 过滤器

c++ - strstr return 如何不是一个常数

function - 定义具有属性 f(a,b,c) = f(c,a,b) = f(b,c,a) 的函数

python - 如何用mongoengine做 "insert if not exist else update"?

python - 三维数组作为向量和矩阵的乘法

python - 如何串联或取消串联 pandas 数据框中的字符串值?

regex - Sed 用另一个字符的多次重复替换一个字符的多次重复

regex - 如果以逗号结尾,如何从 Google Sheets 单元格的末尾删除逗号?

Python,想要使用日志轮换和压缩进行日志记录

python - 如何在 Python 中拆分和解析字符串?