在印刷声明中,我在句子中提到了两只“猫”如何获得此功能来替换第二个“猫”?

问题描述

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"))

输出:

正在下雨的猫和狗