pythonmethodswhile-loop

Using the .find() function in a loop


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.


Solution

  • If you want to find last word then you could use .rfind() which searchs from right to left.

    It doesn't need to use loop for this. And it keeps original sentence.

    sentence = "please write a program which keeps asking the user for words"
    pos = sentence.rfind(" ")     # 54
    last_word = sentence[pos+1:]  # [55:]
    

    In original code problem is that you change sentence (it is shorter and shorter) but in every loop it calculates again len(sentence) and it has different value but index is bigger and bigger.

    If you would add print() then you would see it.

    print(f"{index} | {len(sentence)} | {sentence:60} | {substring} | {sentence[substring+1:]}")
    
    # index | len | sentence | substring | new sentence
    
    0 | 60 | please write a program which keeps asking the user for words | 6 | write a program which keeps asking the user for words
    1 | 53 | write a program which keeps asking the user for words        | 5 | a program which keeps asking the user for words
    2 | 47 | a program which keeps asking the user for words              | 1 | program which keeps asking the user for words
    3 | 45 | program which keeps asking the user for words                | 7 | which keeps asking the user for words
    4 | 37 | which keeps asking the user for words                        | 5 | keeps asking the user for words
    5 | 31 | keeps asking the user for words                              | 5 | asking the user for words
    6 | 25 | asking the user for words                                    | 6 | the user for words
    7 | 18 | the user for words                                           | 3 | user for words
    8 | 14 | user for words                                               | 4 | for words
    sentence = 'for words'
    

    Full code for previous result:

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

    You should get len(sentence) before loop and assign to variable.

    But it may have other problem with value.
    It repeates the same code after it already found last word.

    # index | len | sentence | substring | new sentence
    
    0 | 60 | please write a program which keeps asking the user for words | 6 | write a program which keeps asking the user for words
    1 | 53 | write a program which keeps asking the user for words        | 5 | a program which keeps asking the user for words
    2 | 47 | a program which keeps asking the user for words              | 1 | program which keeps asking the user for words
    3 | 45 | program which keeps asking the user for words                | 7 | which keeps asking the user for words
    4 | 37 | which keeps asking the user for words                        | 5 | keeps asking the user for words
    5 | 31 | keeps asking the user for words                              | 5 | asking the user for words
    6 | 25 | asking the user for words                                    | 6 | the user for words
    7 | 18 | the user for words                                           | 3 | user for words
    8 | 14 | user for words                                               | 4 | for words
    9 | 9 | for words                                                    | 3 | words
    10 | 5 | words                                                        | -1 | words
    11 | 5 | words                                                        | -1 | words
    12 | 5 | words                                                        | -1 | words
    13 | 5 | words                                                        | -1 | words
    14 | 5 | words                                                        | -1 | words
    15 | 5 | words                                                        | -1 | words
    16 | 5 | words                                                        | -1 | words
    17 | 5 | words                                                        | -1 | words
    18 | 5 | words                                                        | -1 | words
    .
    .
    .
    57 | 5 | words                                                        | -1 | words
    58 | 5 | words                                                        | -1 | words
    59 | 5 | words                                                        | -1 | words
    sentence = 'words'
    

    Code:

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

    I would check if find() returns -1 which means it didn't find space in sentence

    sentence = "please write a program which keeps asking the user for words"
    
    while True:
        substring = sentence.find(" ")
        if substring < 0:
            break
        print(f" - | {len(sentence)} | {sentence:60} | {substring} | {sentence[substring+1:]}")
        sentence = sentence[substring+1:]
    
    print(f"{sentence = }")
    

    Result:

    # no index | len | sentence | substring | new sentence
    
     - | 60 | please write a program which keeps asking the user for words | 6 | write a program which keeps asking the user for words
     - | 53 | write a program which keeps asking the user for words        | 5 | a program which keeps asking the user for words
     - | 47 | a program which keeps asking the user for words              | 1 | program which keeps asking the user for words
     - | 45 | program which keeps asking the user for words                | 7 | which keeps asking the user for words
     - | 37 | which keeps asking the user for words                        | 5 | keeps asking the user for words
     - | 31 | keeps asking the user for words                              | 5 | asking the user for words
     - | 25 | asking the user for words                                    | 6 | the user for words
     - | 18 | the user for words                                           | 3 | user for words
     - | 14 | user for words                                               | 4 | for words
     - |  9 | for words                                                    | 3 | words
    sentence = 'words'
    

    The same without changing sentence but using find(..., start_position)

    
    sentence = "please write a program which keeps asking the user for words"
    
    start = 0
    while True:
        pos = sentence.find(" ", start)
        if pos < 0:
            last_word = sentence[start:]
            break
        start = pos+1
        print(f" - | {len(sentence)} | {sentence:60} | {start} | {sentence[start:]}")
    
    print(f"{last_word = }")
    

    Result:

    # no index | len | sentence | start | sentence[start:]
    
     - | 60 | please write a program which keeps asking the user for words | 7 | write a program which keeps asking the user for words
     - | 60 | please write a program which keeps asking the user for words | 13 | a program which keeps asking the user for words
     - | 60 | please write a program which keeps asking the user for words | 15 | program which keeps asking the user for words
     - | 60 | please write a program which keeps asking the user for words | 23 | which keeps asking the user for words
     - | 60 | please write a program which keeps asking the user for words | 29 | keeps asking the user for words
     - | 60 | please write a program which keeps asking the user for words | 35 | asking the user for words
     - | 60 | please write a program which keeps asking the user for words | 42 | the user for words
     - | 60 | please write a program which keeps asking the user for words | 46 | user for words
     - | 60 | please write a program which keeps asking the user for words | 51 | for words
     - | 60 | please write a program which keeps asking the user for words | 55 | words
    last_word = 'words'
    

    All versions in one file:

    (so everyone can simply copy and test it)

    print('\n--- variable `length` ---\n')
    
    sentence = "please write a program which keeps asking the user for words"
    index = 0
    
    substring = sentence.find(" ")
    
    length = len(sentence)
    while index < length:
    #while index < len(sentence):
        substring = sentence.find(" ")
        print(f"{index:2} | {len(sentence):2} | {sentence:60} | {substring:2} | {sentence[substring+1:]}")
        sentence = sentence[substring+1:]
        index += 1
    
    print()
    print(f"{sentence = }")
    
    print('\n--- rfind() ---\n')
    
    sentence = "please write a program which keeps asking the user for words"
    pos = sentence.rfind(" ")
    last_word = sentence[pos+1:]
    
    print(f"{last_word = }")
    print(f"{sentence = }")
    
    print('\n--- find() < 0 ---\n')
    
    sentence = "please write a program which keeps asking the user for words"
    
    while True:
        substring = sentence.find(" ")
        if substring < 0:
            break
        print(f" - | {len(sentence):2} | {sentence:60} | {substring:2} | {sentence[substring+1:]}")
        sentence = sentence[substring+1:]
    
    print()
    print(f"{sentence = }")
    
    print('\n--- find(..., start) < 0 ---\n')
    
    sentence = "please write a program which keeps asking the user for words"
    
    start = 0
    while True:
        pos = sentence.find(" ", start)
        if pos < 0:
            last_word = sentence[start:]
            break
        start = pos+1
        print(f" - | {len(sentence):2} | {sentence:60} | {start:2} | {sentence[start:]}")
    
    print()
    print(f"{last_word = }")
    print(f"{sentence = }")