[Python] Using the .find() function in a loop

Discussão em 'Python' iniciado por Stack, Julho 14, 2025.

  1. Stack

    Stack Membro Participativo

    I was trying to get the last word of the sentence using the .find() method in a loop. My code:

    sentence = "please write a program which keeps asking the user for words"
    index = 0
    substring = sentence.find(" ")
    while index < len(sentence):
    substring = sentence.find(" ")
    sentence = sentence[substring+1:]
    index += 1
    print(sentence)


    This code works when the sentence is:

    sentence = "it was a dark and stormy python"


    but it doesn't work when the sentence is:

    sentence = "please write a program which keeps asking the user for words"


    I want to know why that is and what will be the correct way to do this without using .split().

    I expect the code to output the last word in the sentence.

    Continue reading...

Compartilhe esta Página