Get the length of an Integer in Python

avatar

Borislav Hadzhiev

Last updated: Jun 14, 2022

banner

Photo from Unsplash

Get the length of an Integer in Python #

To get the length of an integer in Python:

  1. Use the str() class to convert the integer to a string, e.g. result = str(my_int).
  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_int = 1234 my_str = str(my_int) print(len(my_str)) # 👉️ 4

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 as 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_int = -1234 if my_int < 0: result = len(str(my_int)) - 1 else: result = len(str(my_int)) print(result) # 👉️ 4

We check if the integer 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_int = 0 if my_int < 0: result = len(str(my_int)) - 1 elif my_int == 0: result = 0 else: result = len(str(my_int)) print(result) # 👉️ 0

The if statement checks if the number is less than 0, and if it is, it subtracts 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_int = 123 result = len(f'{my_int}') print(result) # 👉️ 3

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

main.py
my_str = 'is subscribed:' my_bool = True result = f'{my_str} {my_bool}' print(result) # 👉️ is subscribed: True

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.