简体   繁体   English

如何计算 python 中带前导零的数字的位数

[英]How can I count the digits of a number with leading zeroes in python

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但如果使用带有前导零的数字,如“0001”,我会得到

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?实现这一目标的最佳方法是什么?

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))
leading zeros: 3

If you only wanted the number from a bad input, int() can directly convert it for you instead如果您只想要来自错误输入的数字,则int()可以直接为您转换它

>>> int("0001")
1

I'm dumb.我很笨The answer was simple.答案很简单。 All I needed was:我所需要的只是:

num = 0001
num_string = str(num) 
print (len(num_string))

result:结果:

>>> 4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM