如何通过添加零来获得正好4位数的输出?

Pyt*_*ast -1 python

我想打印输出4位数.

例如,使用16/2,输出应该是0008.

我该怎么做?

unu*_*tbu 6

>>> '{:04d}'.format(16/2)
'0008'
Run Code Online (Sandbox Code Playgroud)

字符串格式04d表示:

0 -- fill spaces with 0
4 -- width should be 4 (though can be greater if the input requires it)
d -- format the input as an integer
Run Code Online (Sandbox Code Playgroud)

有关格式字符串语法的详细信息,请参阅此页面.


ars*_*jii 5

str.zfill() 更适合这个:

>>> str(16/2).zfill(4)
'0008'
Run Code Online (Sandbox Code Playgroud)

str.zfill(width)

返回长度的串填充零的数字串左宽度.正确处理符号前缀.如果width小于或等于,则返回原始字符串len(s).