首页 > 解决方案 > 如何替换字符串中第 N 次出现的单词?

问题描述

对于给定的字符串,如何使用 Python3 将第 N 次出现的单词(子字符串)替换为不同的单词

例子

对于字符串 'here i have the word here 3 times have here' 将单词 'here' 的第二次出现替换为单词 'have' 创建一个新字符串 'here i have the word have 3 times have here'

string = 'here i have the word here 3 times have here'
old_word = 'here'
new_word = 'have'
position = 2 #second appearance
new_string = replacement_function(string, old_word, new_word, position)
print(new_string )

输出:

'here i have the word have 3 times have here'

标签: python

解决方案


s = 'I have a banana and a banana and another banana'
word = 'banana'
replace_with = 'apple'
occurrance  = 2
word.join(s.split(word)[:occurrance]) + replace_with + word.join(s.split(word)[occurrance:])
'I have a banana and a apple and another banana'

如果您只想处理最后一次发生,那么请occurrance = -1


推荐阅读