提问人:jacob Czajka 提问时间:12/21/2022 最后编辑:wovanojacob Czajka 更新时间:12/22/2022 访问量:54
仅替换字符串中最后一个匹配的单词
Replace only the last matching word in a string
问:
我希望结果有结果说.我只能弄清楚如何替换所有出现的,而不仅仅是替换最后一个。我正在尝试通过索引和切片来做到这一点,但我无法弄清楚,解释将不胜感激。"Instead of ice I want pizza"
"ice"
def replace_last_word(sentence, old, new):
if sentence.endswith(old):
i = sentence.index(old)
new_sentence = (sentence[:i] + new)
return new_sentence
return sentence
print(replace_last_word("Instead of ice I want ice", "ice", "pizza"))
答:
1赞
Unmitigated
12/21/2022
#1
使用 (而不是 ) 从末尾开始搜索。rindex
index
i = sentence.rindex(old)
如果要替换的字符串并不总是在末尾,则必须附加剩余的切片。
def replace_last_word(sentence, old, new):
i = sentence.rfind(old)
if i != -1:
sentence = sentence[:i] + new + sentence[i+len(old):]
return sentence
评论
0赞
Selcuk
12/21/2022
然后呢?如果不是句子的最后一个字怎么办?ice
0赞
Unmitigated
12/21/2022
@Selcuk 考虑到问题中的代码已经检查了这一事实,这似乎不是问题。if sentence.endswith(old)
1赞
Selcuk
12/21/2022
公平点,但显然问题中的代码无法正常工作。
0赞
Yash Mehta
12/21/2022
#2
通过将句子转换为单词列表,检查旧单词是否存在于单词列表中,从头到尾迭代,如果存在,只需更改该单词并打破循环。或者,如果不是,就打印相同的句子
法典:-
def replace_last_word(sentence, old, new):
sentence=sentence.split()
for i in range(len(sentence)-1,-1,-1):
if sentence[i]==old:
sentence[i]=new
break
return " ".join(sentence)
print(replace_last_word("Instead of ice i want ice", "ice", "pizza"))
2赞
Selcuk
12/21/2022
#3
可以使用负步长切片来反转字符串,然后利用字符串方法的 count
参数:.replace()
def replace_last_word(sentence, old, new):
return sentence[::-1].replace(old[::-1], new[::-1], 1)[::-1]
然后,您的程序应打印:
'Instead of ice i want pizza'
如果句子不以关键字结尾,它也将起作用:
print(replace_last_word("Instead of ice i want ice and coke", "ice", "pizza"))
Instead of ice i want pizza and coke
评论