Search code examples
pythoncountingleading-zero

Counting leading zeros


I have a basic function:

    return len(a) - len(str(int(a)))

When this is run against the value of: 0000
It returns 3 rather than 4.

I really do not understand why, can someone please clarify?


Solution

  • Try this:

    if int(a) == 0:
        nb_zeros = len(a)
    else:
        nb_zeros = len(a) - len(str(int(a)))
    
    print(nb_zeros)