Find the number of Digits in a number in Python

avatar

Borislav Hadzhiev

Last updated: Jul 3, 2022

banner

Photo from Unsplash

Find the number of digits in a number in Python #

To find the number of digits in a number:

  1. Use the str() class to convert the number to a string.
  2. Pass the string to the len() function, e.g. len(my_str).
  3. The len() function will return the length of the string.
main.py
my_num = 135 my_str = str(my_num) print(len(my_str)) # 👉️ 3

The len() function returns the length (the number of items) of an object.

The argument the function takes may be a sequence (a string, tuple, list, range or bytes) or a collection (a dictionary, set, or frozen set).

This is why we had to convert the integer to a string - we can't pass an integer to the len() function because integers are not a sequence or a collection.

If you need to handle a scenario where the number is negative, subtract 1 from the result.

main.py
my_num = -135 if my_num < 0: result = len(str(my_num)) - 1 else: result = len(str(my_num)) print(result) # 👉️ 3

We check if the number is less than 0, and if it is, we subtract 1 from its length to account for the minus - sign.

If your application considers the number 0 to have a length of 0, add an elif statement to check for 0.

main.py
my_num = 0 if my_num < 0: result = len(str(my_num)) - 1 elif my_num == 0: result = 0 else: result = len(str(my_num)) print(result) # 👉️ 0

The if statement checks if the number is less than 0, and if it is, we subtract 1.

The elif statement checks if the number is equal to 0, and if it is, we assign 0 to the result variable.

If the else statement runs, the integer is positive, so we can convert it to a string and pass the string to the len() function.

You can also use a formatted string literal to get the length of an integer.

main.py
my_num = 135 result = len(f'{my_num}') print(result) # 👉️ 3

Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f.

main.py
name = 'Alice' age = 30 result = f'{name} is {age} years old' print(result) # 👉️ Alice is 30 years old

Make sure to wrap expressions in curly braces - {expression}.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.