显示带前导零的数字

1388

如何在所有小于两位数的数字前显示前导零?

1    →  01
10   →  10
100  →  100
19个回答

9
你可以使用来完成这个操作。
import numpy as np

print(f'{np.random.choice([1, 124, 13566]):0>8}')

这将会打印出长度为8的常量,并在其余部分填充前导的0

00000001
00000124
00013566

8
我是如何做到的:

以下是我的方法:

str(1).zfill(len(str(total)))

基本上zfill接受你想要添加的前导零的数量,所以很容易将最大数字转换为字符串并获取其长度,像这样:
Python 3.6.5 (默认, May 11 2018, 04:00:52) [GCC 8.1.0] 在 linux 上 键入 "help"、"copyright"、"credits" 或 "license" 获取更多信息。 >>> 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

这难道不与Datageek的回答相矛盾吗? - Peter Mortensen
zfill函数接受一个参数,用于指定要添加的前导零的数量。但这个说法是不正确的。实际上,zfill函数会一直添加前导零,直到整个字符串达到所需的长度为止。例如,"10".zfill(2)不会添加任何零。 - undefined

6

4
您也可以这样做:
'{:0>2}'.format(1)

这将返回一个字符串。


print(f'{VALUE:0>5}') 也可以正常工作。 - SimoX

4
width = 5
num = 3
formatted = (width - len(str(num))) * "0" + str(num)
print formatted

2

使用:

'00'[len(str(i)):] + str(i)

或者使用 math 模块:

import math
'00'[math.ceil(math.log(i, 10)):] + str(i)

2
所有这些都会创建字符串“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

1
这是Python的方式,尽管为了清晰起见,我会包括参数 - "{0:0>2}".format(number),如果有人想要nLeadingZeros,他们也可以这样做:" {0:0>{1}}".format(number, nLeadingZeros + 1)。

-2
如果处理的数字是一位或两位数: '0'+str(number)[-2:]'0{0}'.format(number)[-2:]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接