如何在所有小于两位数的数字前显示前导零?
1 → 01
10 → 10
100 → 100
import numpy as np
print(f'{np.random.choice([1, 124, 13566]):0>8}')
这将会打印出长度为8的常量,并在其余部分填充前导的0
。
00000001
00000124
00013566
以下是我的方法:
str(1).zfill(len(str(total)))
使用格式化字符串 - http://docs.python.org/lib/typesseq-strings.html
例如:
python -c 'print "%(num)02d" % {"num":5}'
'{:0>2}'.format(1)
这将返回一个字符串。
width = 5
num = 3
formatted = (width - len(str(num))) * "0" + str(num)
print formatted
使用:
'00'[len(str(i)):] + str(i)
或者使用 math
模块:
import math
'00'[math.ceil(math.log(i, 10)):] + str(i)
>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
'0'+str(number)[-2:]
或 '0{0}'.format(number)[-2:]
"10".zfill(2)
不会添加任何零。 - undefined