Python Count the Number of Digits in a Number
We can easily determine the number of digits in 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
print(f"The number {number} has {count_digits(number)} digits.")
return len(str(number))
# Example usage
number = 12345
print(f"The number {number} has {count_digits(number)} digits.")
Code explanation:
str(number): Convert the number to a string so that we can use the string's length function.len(...): Count the length of the string, which is the number of digits.count_digits(number): Call the function and pass in the number; it returns the number of digits.
Output result:
The number 12345 has 5 digits.Other extensions
Python3 Examples