PythonMastery

Count the digits in a number in Python

Count how many digits a whole number has with a while loop, or with len(str()). Handles 0 and negative numbers correctly.

The number 987654321 has 9 digits. This page counts them with a loop, and then with a string.

The program

python
n = int(input("Enter a whole number: "))

number = abs(n)
count = 0
while True:
    count += 1
    number //= 10
    if number == 0:
        break

print(f"{n} has {count} digits")

Typed in this example: -98765. Press Run to type your own.

output
Enter a whole number: -98765
-98765 has 5 digits

How it works

Another way: len(str())

python
for n in [987654321, -98765, 0, 7]:
    print(n, len(str(abs(n))))
output
987654321 9
-98765 5
0 1
7 1

str() turns the number into text and len() counts the characters. Without abs(), len(str(-98765)) would be 6, because the minus sign is a character too.

Learn the idea: Loops: for, while, and the Pythonic Patterns, Working with Strings