Python counting the digits of a number
We can easily determine the number of digits of a number by converting it to a string and then counting the length of the string. This method is simple and intuitive.
Example
def
count_digits
(
number
)
:
return
len
(
str
(
number
)
)
Example usage
number
=
12345
(
f
"The number {number} has {count_digits(number)} digits."
)
Code analysis:
str(number): convert the number to a string so that we can use the string's length function.len(...): calculate the length of the string, which is the number of digits.count_digits(number): call the function with the number and return its digit count.
Output result:
The number 12345 has 5 digits.
Python3 Examples