Python add leading zeroes using str.format [duplicate]

末鹿安然 提交于 2019-12-17 17:27:05

问题


Can you display an integer value with leading zeroes using the str.format function?

Example input:

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

Desired output:

"001"
"010"
"100"

I know that both zfill and %-based formatting (e.g. '%03d' % 5) can accomplish this. However, I would like a solution that uses str.format in order to keep my code clean and consistent (I'm also formatting the string with datetime attributes) and also to expand my knowledge of the Format Specification Mini-Language.


回答1:


>>> "{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



回答2:


Derived from Format examples, Nesting examples in the Python docs:

>>> '{0:0{width}}'.format(5, width=3)
'005'


来源:https://stackoverflow.com/questions/17118071/python-add-leading-zeroes-using-str-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!