In a number without leading zeroes I would do this
import math
num = 1001
digits = int(math.log10(num)) 1
print (digits)
>>> 4
but if use a number with leading zeroes like "0001" I get
SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers
I would like to be able to count the digits including the leading zeroes. What would be the best way to achieve this?
CodePudding user response:
You can't reasonably have a number with leading digits unless it's a string!
Therefore, if you're accepting a string, just remove them and check the difference in length
>>> value = input("enter a number: ")
enter a number: 0001
>>> value_clean = value.lstrip("0")
>>> leading_zeros = len(value) - len(value_clean)
>>> print("leading zeros: {}".format(leading_zeros))
3
If you only wanted the number from a bad input, int()
can directly convert it for you instead
>>> int("0001")
1
CodePudding user response:
I'm dumb. The answer was simple. All I needed was:
num = 0001
num_string = str(num)
print (len(num_string))
result:
>>> 4