How to Count Digits in Python
The Python computer programming language includes string and numeric variables. Strings can contain alphabet letters and symbols in conjunction with numbers, while numeric variables can only contain numbers. The method required to count digits in a variable differs based on whether you are dealing with a string or numeric variable. For a string, you would use the integrated 'len' function. For a numeric variable, however, you would need to import the 'math' module.
Instructions
-
Count Numerical Variable Digits
-
1
Define a numeric variable to store the digit count value:
counter = 0
-
2
Import the 'math' module:
import math
-
-
3
Call the 'log10' function from the 'math' module and wrap it around the 'integer' function. Assign the value to the counter variable.
counter = int(math.log10(NumVar))+1
-
4
Replace 'NumVar' with the numerical variable you want to analyze, and print the result using the 'print' function:
print counter
Count String Variable Digits
-
5
Define a numerical variable to store the digit count:
counter = 0
-
6
Encapsulate the variable you would like to analyze in the 'len' function and assign the result to the counter variable:
counter = len(NumVar)
-
7
Print the result using the 'print' function:
print counter
-
1