簡體   English   中英

如何計算 python 中帶前導零的數字的位數

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

在沒有前導零的數字中,我會這樣做

import math
num = 1001
digits = int(math.log10(num))+1
print (digits)

>>> 4

但如果使用帶有前導零的數字,如“0001”,我會得到

SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers

我希望能夠計算包括前導零在內的數字。 實現這一目標的最佳方法是什么?

除非它是一個字符串,否則你不能合理地擁有一個帶前導數字的數字!

因此,如果您接受一個字符串,只需刪除它們並檢查長度差異

>>> 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

如果您只想要來自錯誤輸入的數字,則int()可以直接為您轉換它

>>> int("0001")
1

我很笨答案很簡單。 我所需要的只是:

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

結果:

>>> 4

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM