jke*_*ian 79

print "%02d"%a 是python 2变种

python 3使用了一个更冗长的格式化系统:

"{0:0=2d}".format(a)
Run Code Online (Sandbox Code Playgroud)

python2的相关文档链接是:http://docs.python.org/2/library/string.html#format-specification-mini-language

对于python3,它是http://docs.python.org/3/library/string.html#string-formatting

  • 简单地说,`"{:02d}".format(a)` 也可以!如果您想要 4 位数字,只需将 2 替换为 4 `"{:04d}".format(a)`。这是针对Python3的。 (4认同)

tux*_*21b 20

a = 5
print '%02d' % a
# output: 05
Run Code Online (Sandbox Code Playgroud)

当与左侧的字符串一起使用时,'%'运算符称为字符串格式化运算符.'%d'是打印出整数的格式代码(如果值不是数字,则会出现类型错误).随着'%2d您可以指定长度,'%02d'可用于填充字符设置为0,而不是默认的空间.


use*_*312 14

>>> print '{0}'.format('5'.zfill(2))
05
Run Code Online (Sandbox Code Playgroud)

在这里阅读更多.


小智 11

在 Python 3.6 中,您可以使用所谓的 f 字符串。在我看来,这种方法读起来更清晰。

>>> f'{a:02d}'
'05'
Run Code Online (Sandbox Code Playgroud)


小智 7

>>> a=["%02d" % x for x in range(24)]
>>> a
['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23']
>>> 
Run Code Online (Sandbox Code Playgroud)

就是这么简单


小智 6

根据@user225312所说,您可以使用 .zfill() 将 paddng 添加到转换为字符串的数字中。

我的方法是将数字保留为数字,直到您想要将其转换为字符串为止:

>>> num = 11
>>> padding = 3
>>> print(str(num).zfill(padding))
011
Run Code Online (Sandbox Code Playgroud)


小智 5

在 Python3 中,您可以:

print("%02d" % a)
Run Code Online (Sandbox Code Playgroud)