1189

鉴于:

a = 1
b = 10
c = 100

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

这是我期待的输出:

01
10
100
4

17 回答 17

1505

在 Python 2(和 Python 3)中,您可以:

number = 1
print("%02d" % (number,))

基本上%就像printfsprintf(请参阅文档)。


对于 Python 3.+,同样的行为也可以通过以下方式实现format

number = 1
print("{:02d}".format(number))

对于 Python 3.6+,可以使用f-strings实现相同的行为:

number = 1
print(f"{number:02d}")
于 2008-09-25T18:08:21.363 回答
1126

您可以使用str.zfill

print(str(1).zfill(2))
print(str(10).zfill(2))
print(str(100).zfill(2))

印刷:

01
10
100
于 2010-07-30T11:58:30.337 回答
376

在 Python 2.6+ 和 3.0+ 中,您将使用format()string 方法:

for i in (1, 10, 100):
    print('{num:02d}'.format(num=i))

或使用内置(对于单个数字):

print(format(i, '02d'))

有关新的格式化功能,请参阅PEP-3101文档。

于 2008-09-25T18:43:06.460 回答
151
print('{:02}'.format(1))
print('{:02}'.format(10))
print('{:02}'.format(100))

印刷:

01
10
100
于 2013-11-13T19:30:23.083 回答
97

Python >= 3.6中,您可以使用引入的新 f 字符串简洁地做到这一点:

f'{val:02}'

它打印名称为和 aval的变量。fill0width2

对于您的具体示例,您可以在循环中很好地执行此操作:

a, b, c = 1, 10, 100
for val in [a, b, c]:
    print(f'{val:02}')

打印:

01 
10
100

有关 f 字符串的更多信息,请查看引入它们的PEP 498 。

于 2017-11-28T14:52:21.420 回答
90

或这个:

print '{0:02d}'.format(1)

于 2010-11-10T10:03:43.967 回答
68
x = [1, 10, 100]
for i in x:
    print '%02d' % i

结果是:

01
10
100

在文档中阅读有关使用 % 进行字符串格式化的更多信息

于 2008-09-25T18:07:37.170 回答
55

执行此操作的 Pythonic 方式:

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
于 2012-04-27T22:02:37.990 回答
34

或者另一种解决方案。

"{:0>2}".format(number)
于 2015-11-22T21:01:27.677 回答
7

我就是这样做的:

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

基本上 zfill 取你要添加的前导零的数量,所以很容易取最大的数字,把它变成一个字符串并得到长度,像这样:

Python 3.6.5(默认,2018 年 5 月 11 日,04:00:52)
[GCC 8.1.0] 在 Linux 上
输入“帮助”、“版权”、“信用”或“许可”以获取更多信息。
>>> 总计 = 100
>>> 打印(str(1).zfill(len(str(total))))
001
>>> 总计 = 1000
>>> 打印(str(1).zfill(len(str(total))))
0001
>>> 总计 = 10000
>>> 打印(str(1).zfill(len(str(total))))
00001
>>>
于 2018-06-21T00:43:15.873 回答
7

你可以用f strings来做到这一点。

import numpy as np

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

这将打印 8 的恒定长度,并用前导填充其余部分0

00000001
00000124
00013566
于 2020-03-11T18:50:30.170 回答
5

使用格式字符串 - http://docs.python.org/lib/typesseq-strings.html

例如:

python -c 'print "%(num)02d" % {"num":5}'
于 2008-09-25T18:10:01.003 回答
2
width = 5
num = 3
formatted = (width - len(str(num))) * "0" + str(num)
print formatted
于 2013-11-15T16:33:33.573 回答
0

采用:

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

或使用math模块:

import math
'00'[math.ceil(math.log(i, 10)):] + str(i)
于 2018-04-20T13:21:55.293 回答
0

所有这些都创建了字符串“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
于 2021-03-09T18:51:58.277 回答
0

这将是 Python 的方式,尽管为了清楚起见我会包含参数 - “{0:0>2}”.format(number),如果有人想要 nLeadingZeros,他们应该注意他们也可以这样做:“{0:0> {1}}".format(数字,nLeadingZeros + 1)

于 2021-10-02T11:23:45.933 回答
-3

如果处理一位或两位数的数字:

'0'+str(number)[-2:]或者'0{0}'.format(number)[-2:]

于 2016-02-19T04:20:45.753 回答