如何显示小于两位数字的所有数字的前导零?
1 → 01
10 → 10
100 → 100
如何显示小于两位数字的所有数字的前导零?
1 → 01
10 → 10
100 → 100
当前回答
你还可以:
'{:0>2}'.format(1)
它将返回一个字符串。
其他回答
python的方法是:
str(number).rjust(string_width, fill_char)
这样,如果原始字符串的长度大于string_width,则原始字符串将原封不动地返回。例子:
a = [1, 10, 100]
for num in a:
print str(num).rjust(2, '0')
结果:
01
10
100
所有这些都创建了字符串“01”:
>python -m timeit "'{:02d}'.format(1)"
1000000 loops, best of 5: 357 nsec per loop
>python -m timeit "'{0:0{1}d}'.format(1,2)"
500000 loops, best of 5: 607 nsec per loop
>python -m timeit "f'{1:02d}'"
1000000 loops, best of 5: 281 nsec per loop
>python -m timeit "f'{1:0{2}d}'"
500000 loops, best of 5: 423 nsec per loop
>python -m timeit "str(1).zfill(2)"
1000000 loops, best of 5: 271 nsec per loop
>python
Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 23:11:46) [MSC v.1916 64 bit (AMD64)] on win32
在Python 2.6+和3.0+中,你可以使用format()字符串方法:
for i in (1, 10, 100):
print('{num:02d}'.format(num=i))
或者使用内置的(单个数字):
print(format(i, '02d'))
有关新的格式化函数,请参阅PEP-3101文档。
在Python >= 3.6中,您可以使用以下方法引入的新f-string简单地完成此操作:
f'{val:02}'
它输出名为val的变量,填充值为0,宽度为2。
对于你的具体例子,你可以在循环中很好地做到这一点:
a, b, c = 1, 10, 100
for val in [a, b, c]:
print(f'{val:02}')
打印:
01
10
100
有关f-字符串的更多信息,请参阅PEP 498,其中介绍了f-字符串。
我是这样做的:
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 >>>