python - 如何替换字符串中第 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'
解决方案
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
推荐阅读
- python - 如何使函数重复,直到使用 pynput 在 python 上按下特定键?
- firebase - Firebase 函数在接下来的 20 秒内调用
- c++ - 取消引用指向对象的指针以调用构造函数
- java - How can I set the not null field? Spring boot, Hibernate
- php - Xdebug Could not connect to debugging client. Tried: localhost:9000
- python - how to convert .py made with kivy to .exe
- python - How to do a (trapeze) integration in Python without any import?
- python - Apple M1: install psycopg2 package Symbol not found: _PQbackendPID
- javascript - Javascript: add item to Context Menu
- python - Pandas: index-derived column with specific increments based on other columns