是否可以使用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
和%
-based格式化(例如'%03d' % 5
)都可以做到这一点。但是,我希望有一个使用str.format
的解决方案,以便保持代码的整洁和一致(我还使用datetime属性格式化字符串),并扩展我对Format Specification Mini-Language的了解。
发布于 2013-06-15 06:26:21
>>> "{0:0>3}".format(1)
'001'
>>> "{0:0>3}".format(10)
'010'
>>> "{0:0>3}".format(100)
'100'
解释:
{0 : 0 > 3}
│ │ │ │
│ │ │ └─ Width of 3
│ │ └─ Align Right
│ └─ Fill with '0'
└─ Element index
发布于 2013-06-15 06:35:17
派生自Python文档中的Format examples, Nesting examples:
>>> '{0:0{width}}'.format(5, width=3)
'005'
https://stackoverflow.com/questions/17118071
复制相似问题