如何显示小于两位数字的所有数字的前导零?
1 → 01
10 → 10
100 → 100
如何显示小于两位数字的所有数字的前导零?
1 → 01
10 → 10
100 → 100
当前回答
或者另一个解。
"{:0>2}".format(number)
其他回答
我是这样做的:
str(1).zfill(len(str(total)))
基本上zfill取你想加的前导零的个数,所以很容易取最大的数字,把它转换成字符串并得到长度,像这样:
Python 3.6.5 (default, May 11 2018, 04:00:52) [GCC 8.1.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> total = 100 >>> print(str(1).zfill(len(str(total)))) 001 >>> total = 1000 >>> print(str(1).zfill(len(str(total)))) 0001 >>> total = 10000 >>> print(str(1).zfill(len(str(total)))) 00001 >>>
在Python 2(和Python 3)中,您可以执行:
number = 1
print("%02d" % (number,))
基本上%类似于printf或sprintf(参见文档)。
对于Python 3。+,同样的行为也可以通过format实现:
number = 1
print("{:02d}".format(number))
对于Python 3.6+,同样的行为可以通过f-strings实现:
number = 1
print(f"{number:02d}")
你可以使用str.zfill:
print(str(1).zfill(2))
print(str(10).zfill(2))
print(str(100).zfill(2))
打印:
01
10
100
或者另一个解。
"{:0>2}".format(number)
或:
打印“{0:02d}”.format (1)