Counting digits in Python—visualizing different methods through vibrant code and numbers.
Count the Digits in a Number Using Python: Let’s say you have a number—like 12345—and you want to know how many digits are in it.
If you look at it yourself, it’s easy. You just count: 1, 2, 3, 4, 5. That’s 5 digits.
But how do we make Python do that for us?
In this guide, I’ll show you a few ways to count digits in a number using Python. You’ll learn:
Let’s start with the easiest method.
len() and str()This is one of the easiest ways to count digits in Python. It’s perfect if you’re just getting started.
Let’s say you have a number, like:
94527
You want to know how many digits are in it. Here’s how to do it step by step.
In Python, we can turn numbers into strings using the str() function. Like this:
str(94527)
This gives you: "94527"
Now, it’s a string with 5 characters.
To count the characters, we use the len() function:
len(str(94527))
This tells us the answer is 5.
And that’s it! Python has counted the digits for you.
So to repeat:
You can try it with any number:
len(str(2025)) # This will give you 4
len(str(1000000)) # This will give you 7
This method works well as long as the number is positive.
Let’s say you have a number:
n = -12345
If you do this:
len(str(n))
It will return 6, not 5. Why?
Because it’s counting the minus sign too.
To fix that, we can first turn the number positive using abs(). That way, we only count the digits—not the sign.
Here’s the full code:
n = -12345
n = abs(n) # Remove the minus sign
digit_count = len(str(n)) # Count digits
print("Number of digits:", digit_count)
Output:
Number of digits: 5
Easy and clean!
This works great for any integer, whether positive or negative.
This time, we’ll use math to break down the number one digit at a time.
Let’s say you have a number like this:
n = 94527
Here’s the idea:
We’ll divide the number by 10 again and again until it becomes 0.
Each time we divide, we remove one digit from the end.
And for every division, we add 1 to our count.
Let me show you the code first:
n = 94527
count = 0
while n > 0:
n = n // 10 # Remove the last digit
count += 1 # Add 1 to the digit count
print("Number of digits:", count)
94527.//. This removes the last digit: In this case, the output will be:
Number of digits: 5
Let’s now talk about how to count digits in:
We’ll handle each one step by step.
Let’s say you have:
n = -1234
The minus sign isn’t a digit—it’s just telling us the number is negative. So first, we’ll ignore the sign by taking the absolute value using Python’s abs() function.
Here’s the updated code:
n = -1234
n = abs(n) # Make it positive
count = 0
while n > 0:
n = n // 10
count += 1
print("Number of digits:", count)
Output:
Number of digits: 4
So just add n = abs(n) before your loop, and it’ll work with negative numbers too.
This one’s a little different. A float has digits before and after the decimal point. So you’ll need to decide:
Do you want to count only the digits, or include the decimal point too?
Let’s say you only want to count digits (no decimal point). Here’s how to do it:
n = 123.45
# Remove the decimal by converting to string
s = str(n)
# Remove the dot
s = s.replace('.', '')
# Count the digits
print("Number of digits:", len(s))
Output:
Number of digits: 5
If you want to use math instead of strings for floats, it’s much trickier and not as reliable due to rounding issues. So it’s best to use the string method for floats.
Let’s say:
n = -78.910
You can use the same idea:
n = abs(n) # Remove the minus sign
s = str(n)
s = s.replace('.', '') # Remove the decimal point
print("Number of digits:", len(s))
Output:
Number of digits: 5
(7, 8, 9, 1, 0)
def count_digits(number):
# Handle negative numbers
number = abs(number)
# Check if the number is a float
if isinstance(number, float):
# Convert to string, remove the decimal point
s = str(number).replace('.', '')
return len(s)
else:
# Integer case: use math (no string conversion)
count = 0
if number == 0:
return 1 # Special case for 0
while number > 0:
number = number // 10
count += 1
return count
print(count_digits(94527)) # Output: 5
print(count_digits(-1234)) # Output: 4
print(count_digits(0)) # Output: 1
print(count_digits(123.45)) # Output: 5
print(count_digits(-78.910)) # Output: 5
This function handles most common cases cleanly and returns the total number of digits—ignoring the minus sign and decimal point.
Now let’s explore how to use logarithms is an efficient way to count digits, especially when dealing with large numbers. The idea behind this method is based on how numbers work in base 10.
The logarithm (base 10) of a number tells us how many times the number can be divided by 10 before it reaches 1. This can help us figure out the number of digits in a number.
For example:
Let me show you how to implement this method.
0 needs special treatment because the logarithm of 0 is undefined.Here’s how we can do it:
import math
def count_digits_log(n):
# Handle the edge case where the number is 0
if n == 0:
return 1
# Take the absolute value to ignore the negative sign
n = abs(n)
# Apply the logarithm and add 1 to get the number of digits
return math.floor(math.log10(n)) + 1
print(count_digits_log(94527)) # Output: 5
print(count_digits_log(-1234)) # Output: 4
print(count_digits_log(0)) # Output: 1
print(count_digits_log(12345)) # Output: 5
print(count_digits_log(1000000)) # Output: 7
This method is very efficient, especially for large numbers, because it avoids looping through the digits. Instead, it only requires a couple of mathematical operations.
Ready to put your skills to the test? Try these practice problems to strengthen your understanding of counting digits in Python. These are perfect for learners who want to go beyond the basics.
Write a function that takes a list of integers and returns a list of digit counts.
Example:
Input:
[123, 0, 99999, -78]
Output:
[3, 1, 5, 2]
Hint: You can use either str(), loops, or math.log10 — your choice!
Write a program that filters out numbers from a list that don’t have exactly N digits.
Example:
If N = 4 and the list is [23, 1456, 8765, 12, 999], your output should be:
[1456, 8765]
Bonus: Try it without converting numbers to strings.
Write a function that takes a list of numbers and returns the total number of digits across all of them (ignoring minus signs and decimal points).
Example:
Input: [123.45, -67, 8900]
Output: 9 (digits are: 1,2,3,4,5,6,7,8,9 — decimal and minus ignored)
Ask the user to enter numbers separated by spaces, then print how many digits each one has.
Example:
Input:
Please enter numbers: 34 -56 7.89 10000
Output:
34 → 2 digits
-56 → 2 digits
7.89 → 3 digits
10000 → 5 digits
Bonus: Add exception handling to skip invalid inputs.
Write a function called count_digits_custom that:
Example:
Input: [“1,000”, “$23.45”, “-89”, 300]
Output: [4, 4, 2, 3]
Challenge yourself: Don’t use len(str(x)) directly inside your logic.
🔥 Bonus Challenge: Count Digits Without Any Loops or Strings
Can you count the number of digits in a positive integer using only math and recursion (no while or for loops, and no str())?
Counting digits in a number may seem like a small task, but as you’ve seen, there are several smart ways to approach it in Python. Whether you:
math.log10 for large numbers,you now have a solid toolbox of techniques that work for integers, floats, negatives, and even mixed inputs.
This kind of problem strengthens your understanding of Python’s core features—like type conversion, math functions, conditionals, and loops—while also helping you write cleaner and more efficient code.
Tip: Try combining these techniques in creative ways. For instance, how would you count digits in a nested list of numbers? Or sort numbers based on how many digits they have?
If you haven’t already, head over to the challenge section above and tackle those exercises. They’re designed to stretch your logic and make sure you truly understand the concepts—not just memorize them.
We’d love to hear from you! Drop your thoughts in the comments or share your code with us on LinkedIn. Teaching others is the best way to master a topic.
Want more Python tricks like this?
Visit us at emitechlogic.com for deep, practical guides that make Python easier to learn and more fun to use.
You can use len(str(number)) to count the digits. For example, len(str(12345)) returns 5.
Use a loop and divide the number by 10 repeatedly until it becomes 0. Count how many times you do it. Or use math.log10 for a quicker method.
Yes—if you convert to a string, you’ll need to remove ‘-‘ and ‘.’ before counting. With math or loops, these characters don’t matter.
Yes, but you’ll need to remove the decimal point first. You can do this by converting to a string and using replace(“.”, “”) or multiplying by 10^n if using math.
Python’s str() function:
https://docs.python.org/3/library/functions.html
len() function for counting characters:
https://docs.python.org/3/library/functions.html
math.log10() for digit counting:
https://docs.python.org/3/library/math.html
We don’t just show you the code—we let you run it too!
Thanks to embedded tools from Trinket.io, you can practice the examples from this blog post right on the page—no need to install anything.
After debugging production systems that process millions of records daily and optimizing research pipelines that…
The landscape of Business Intelligence (BI) is undergoing a fundamental transformation, moving beyond its historical…
The convergence of artificial intelligence and robotics marks a turning point in human history. Machines…
The journey from simple perceptrons to systems that generate images and write code took 70…
In 1973, the British government asked physicist James Lighthill to review progress in artificial intelligence…
Expert systems came before neural networks. They worked by storing knowledge from human experts as…
This website uses cookies.