80

str.format您可以使用该函数显示带有前导零的整数值吗?

示例输入:

"{0:some_format_specifying_width_3}".format(1)
"{0:some_format_specifying_width_3}".format(10)
"{0:some_format_specifying_width_3}".format(100)

期望的输出:

"001"
"010"
"100"

我知道基于zfill%的格式(例如'%03d' % 5)都可以做到这一点。但是,我想要一个解决方案,str.format以保持我的代码干净和一致(我还使用 datetime 属性格式化字符串)并扩展我对Format Specification Mini-Language的知识。

4

2 回答 2

197
>>> "{0:0>3}".format(1)
'001'
>>> "{0:0>3}".format(10)
'010'
>>> "{0:0>3}".format(100)
'100'

Explanation:

{0 : 0 > 3}
 │   │ │ │
 │   │ │ └─ Width of 3
 │   │ └─ Align Right
 │   └─ Fill with '0'
 └─ Element index
于 2013-06-14T22:26:20.647 回答
27

派生自格式示例, Python 文档中的嵌套示例:

>>> '{0:0{width}}'.format(5, width=3)
'005'
于 2013-06-14T22:35:16.630 回答