In the print statement, I have two "cats" mentioned in my sentence. How do I get this function to replace the second "cats"?

Viewed 40
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"))
1 Answers

You just need to use rindex instead of index, to get the index of the last occurrence:

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

Output:

It's raining cats and dogs

Related