Python Count the Number of Digits present in a Number

In this tutorial, we will learn how to count the number of digits present in a number in Python. We will cover the basic concept of number manipulation and implement a function to perform the counting.

What is Number Manipulation

Number manipulation involves performing operations on numbers to achieve a specific result. Counting the number of digits in a number is a common task in number manipulation.

Syntax

The syntax to count the number of digits in a number in Python is:

def count_digits(n):
return len(str(n))

Counting the number of digits in a number

We can create a function to count the number of digits in a given number by converting it to a string and getting the length of the string.

For example,

Define a function named count_digits that takes one parameter n.

Convert the number to a string using the str function.

Get the length of the string using the len function.

Return the length of the string, which represents the number of digits in the number.

Call the function with a sample number and print the result.

Python Program

def count_digits(n):
return len(str(n))
# Sample number
sample_number = 12345
# Count the number of digits
result = count_digits(sample_number)
# Print the result
print('Number of digits in', sample_number, 'is:', result)