83

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.

butch
  • 2,178
  • 1
  • 17
  • 21
  • 1
    Are `max_width`, `a`, `b`, and `c` variable names or is your input a string? – Andrew Clark Jun 14 '13 at 22:19
  • Those are just some example variable names. `max_width` was used for the example to indicate how many leading zeroes would be necessary for the example values. In my actual code the input to format includes a datetime object and some ints that I would like to format with leading zeroes. – butch Jun 14 '13 at 22:22
  • so you want a 1-liner with `format` or a function that uses nothing but raw python would suffice? – Ryan Saxe Jun 14 '13 at 22:24
  • Yes I am asking if it is possible (and how) to do it with just `format`. – butch Jun 14 '13 at 22:26

2 Answers2

204
>>> "{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
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
  • Ah, I think my examples were interpreted a bit too literally. I simply want a format that makes `"{0:some_format_specifying_width_four}".format(10)` produce `"0010"`. – butch Jun 14 '13 at 22:30
  • 1
    I updated my original examples to provide more clarity – butch Jun 14 '13 at 22:33
30

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

>>> '{0:0{width}}'.format(5, width=3)
'005'
msw
  • 42,753
  • 9
  • 87
  • 112
  • Excellent! I'm accepting @F.J's answer as I prefer not specifying another variable for width, though this answer does seem very pythonic in its explicitness! – butch Jun 14 '13 at 22:40
  • That will happen when you edit the question after it's been answered. I'm glad we could help you clarify your intention. – msw Jun 14 '13 at 22:52