如何替换字符串中出现的第n个单词?

2024-09-28 13:30:42 发布

您现在位置:Python中文网/ 问答频道 /正文

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

范例

对于字符串“here i have the word here 3次have here”将单词“here”的第二次出现替换为单词“have”creating a new string“here i have the word have 3次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'

Tags: the字符串creatingnewstringherehaveposition
1条回答
网友
1楼 · 发布于 2024-09-28 13:30:42
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

相关问题 更多 >

    热门问题