In Python, numeric types like integers (int) and floats (float) are not sequences, so they do not have a "length" in the same way that a string or a list does. Attempting to use the built-in len() function on a number will result in a TypeError. However, a common task is to find the number of digits in an integer or float.
The correct way to achieve this is to first convert the number into a string, and then you can find the length of that string. This guide will walk you through the process for both integers and floats, including how to handle negative signs and decimal points.
Understanding the Error: Why len() Fails on Numbers
The len() function is designed to work on objects that have a defined length, known as "sized" objects, which are typically sequences or collections (like strings, lists, tuples, and dictionaries). Numbers represent a single magnitude and are not collections.
Example of code causing the error:
my_number = 12345
length = len(my_number)Output:
Getting the Length of an Integer
Basic Conversion
To get the number of digits in a positive integer, simply convert it to a string and then get the length of that string.
Solution:
my_int = 17635
int_length = len(str(my_int))
print(f"The number of digits in {my_int} is: {int_length}")Output:
The number of digits in 17635 is: 5Handling Negative Integers
If you apply len(str()) to a negative number, the minus sign (-) will be included in the character count. To count only the digits, first get the absolute value of the number using abs().
Solution:
negative_int = -99999
length_with_sign = len(str(negative_int))
print(f"Length including the sign: {length_with_sign}")
length_without_sign = len(str(abs(negative_int)))
print(f"Length of digits only: {length_without_sign}")Output:
Getting the Length of a Float
Including the Decimal Point
When you convert a float to a string, the decimal point (.) is included as a character.
Solution:
my_float = 17.635
float_length = len(str(my_float))
print(f"The total character length of {my_float} is: {float_length}")Output:
Excluding the Decimal Point
To count only the digits in a float, you can remove the decimal point from the string representation using the .replace() method before getting the length.
Solution:
negative_float = -99.9922
float_as_str = str(abs(negative_float))
digits_only_str = float_as_str.replace('.', '')
digit_count = len(digits_only_str)
print(f"The number of digits in {negative_float} is: {digit_count}")Output:
Creating Reusable Functions
For convenience, you can wrap this logic in reusable functions.
Solution:
def get_integer_digit_count(number: int) -> int:
"""Returns the number of digits in an integer, ignoring the sign."""
return len(str(abs(number)))
def get_float_digit_count(number: float) -> int:
"""Returns the number of digits in a float, ignoring the sign and decimal point."""
return len(str(abs(number)).replace('.', ''))
print(f"Integer count for -9999: {get_integer_digit_count(-9999)}")
print(f"Float count for -99.9922: {get_float_digit_count(-99.9922)}")Output:
Conclusion
| To find the number of digits in... | The best solution is... | Example |
|---|---|---|
| A positive integer | Convert to string and get length | len(str(123)) |
| Any integer (ignoring sign) | Use abs() before converting |
len(str(abs(-123))) |
| Any float (ignoring sign and decimal point) | Use abs() and str.replace() |
len(str(abs(-12.3)).replace('.', '')) |
The len() function cannot be used directly on numeric types. The key is to always convert the number to a string first, and then manipulate that string to get the specific count you need.