Home > OS >  sentence = "Instead of ice I want ice"
sentence = "Instead of ice I want ice"

Time:12-21

I want the result to have the result say "Instead of ice I want pizza". I can only figure out how to replace all occurrences of "ice" instead of just replacing the last one. I am trying to do this by indexing and slicing but I cannot figure it out, an explanation would be much appreciated.

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

CodePudding user response:

You can use negative step slicing to reverse strings, then take advantage of the count argument of the string .replace() method:

def replace_last_word(sentence, old, new):
    return sentence[::-1].replace(old[::-1], new[::-1], 1)[::-1]

Your program should then print:

'Instead of ice i want pizza'

It will also work if the sentence does not end with the keyword:

print(replace_last_word("Instead of ice i want ice and coke", "ice", "pizza"))
Instead of ice i want pizza and coke

CodePudding user response:

Use rindex (instead of index) to search from the end.

i = sentence.rindex(old)

If the string to be replaced is not always at the end, you will have to append the leftover slice.

def replace_last_word(sentence, old, new):
    i = sentence.rfind(old)
    if i != -1:
        sentence = sentence[:i]   new   sentence[i len(old):]
    return sentence

CodePudding user response:

By converting sentence into a list of words checking whether the old word present in the list of words iterating from end to start if it present just change that word and break the loop.. or if not just print the same sentence

Code:-

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