How to Count the Number of Digits in Python?

Estimated read time 2 min read

To count the number of digits in a Python integer, you can convert the integer to a string using the str() function and then use a loop to iterate over each character in the string, checking if it is a digit using the isdigit() method.

Here’s an example:

# create a sample integer
my_int = 123456789

# convert the integer to a string
my_str = str(my_int)

# initialize a counter variable
count = 0

# iterate over each character in the string
for char in my_str:
    if char.isdigit():
        count += 1

print(f'The integer {my_int} contains {count} digits.')

In this example, we create a sample integer (123456789) and convert it to a string using the str() function. We then initialize a counter variable to zero and use a loop to iterate over each character in the string. For each character, we check if it is a digit using the isdigit() method. If it is, we increment the counter variable by one.

Finally, we print a message to the console indicating the number of digits in the original integer. The output will be:

The integer 123456789 contains 9 digits.

Note that this approach only works for positive integers. If you need to count the digits in a negative integer, you can first convert it to a positive integer using the abs() function. If you need to count the digits in a floating-point number, you can convert it to a string and then count the digits as above, but you will need to handle the decimal point separately.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply