Python add leading zeroes using str.format

Question:

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.

Asked By: butch

||

Answers:

>>> "{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
Answered By: Andrew Clark

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

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