# Get the length of an Integer in Python Tue Jun 14 20222 min read Photo by Anatol Lem

## 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(result)`.
3. The `len()` function will return the length of the string.
main.py
```Copied!```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
```Copied!```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
```Copied!```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, subtracts `1`.

The `elif` statement checks if the number is equal to `0`, and if it is, assigns `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
```Copied!```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
```Copied!```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}`.

Use the search field on my Home Page to filter through my more than 1,000 articles.