问题描述
def replace_ending(sentence,old,new):
if old in sentence:
i = sentence.index(old)
new_sentence = sentence[:i] + new
return new_sentence
return sentence
#print(replace_ending("It's raining cats and cats","cats","dogs"))
解决方法
您只需要使用rindex
而不是index
来获取最后一次出现的索引:
def replace_ending(sentence,old,new):
if old in sentence:
i = sentence.rindex(old) # this is the only difference
new_sentence = sentence[:i] + new
return new_sentence
return sentence
print(replace_ending("It's raining cats and cats","cats","dogs"))
输出:
正在下雨的猫和狗