Search code examples
pythonloopswhile-loopdigits

Finding first digit index in Python loop?


found = False
position = 0

while not found and position < len(inputString):
    if inputString[position].isdigit():
        found = True
    else:
        position += 1

if found:
    print('first digit is at position', position)
else:
    print('There are no digits in the string')

This is a simple program I found that deals with finding the first digit in an inputted string. Something I am having trouble understanding is...

if inputString[position].isdigit(): found = True

What exactly does this expression state, specifically the inputString[position] part. Are we looking for the position/index value of the first digit and then breaking the loop into the print statement below?


Solution

  • Are we looking for the position/index value of the first digit and then breaking the loop into the print statement below?

    Yes, that's true. It breaks because once a digit is found, in the next iteration while not found condition will give while False and break the while loop. Worth noting and short-circuits, so the second condition is not even evaluated.

    If a digit is not found, position increments until it is equal to len(inputString), at which point the while loop breaks via the second condition, i.e. position < len(inputString).


    A more Pythonic / idiomiatic way to write your while loop is via for loop and enumerate:

    for idx, val in enumerate(inputString, 1):
        if val.isdigit():
            position = idx
            break
    else:
        position = 0
    
    if position:
        print('first digit is at position', position)
    else:
        print('There are no digits in the string')
    

    Notice, in this solution, since we start counting from 1, we can take advantage of the fact if a digit is found it must be "Truthy", i.e. non-zero. Therefore, we don't need an extra found variable.