27

How do I get an integer to fill 0's to a fixed width in python 3.2 using the format attribute? Example:

a = 1
print('{0:3}'.format(a))

gives ' 1' instead of '001' I want. In python 2.x, I know that this can be done using

print "%03d" % number. 

I checked the python 3 string documentation but wasn't able to get this.

http://docs.python.org/release/3.2/library/string.html#format-specification-mini-language

Thanks.

pogo
  • 1,479
  • 3
  • 18
  • 23

4 Answers4

66

Prefix the width with a 0:

>>> '{0:03}'.format(1)
'001'

Also, you don't need the place-marker in recent versions of Python (not sure which, but at least 2.7 and 3.1):

>>> '{:03}'.format(1)
'001'
Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365
  • How does this approach work for a full column, where i have 1, and 211 for example and i want to have the output 001 and 211. Thanks – PV8 Nov 02 '18 at 12:19
18

Better:

number=12
print(f'number is equal to {number:03d}')
Mendi Barel
  • 3,350
  • 1
  • 23
  • 24
13

There is built-in string method .zfill for filling 0-s:

>>> str(42).zfill(5)
'00042'
>>> str(42).zfill(2)
'42'
Aivar Paalberg
  • 4,645
  • 4
  • 16
  • 17
  • This works well in my application, where I need binary numbers: `bin(42)[2:].zfill(7)` gives `'0101010'`. I don't know how'd I'd make the other answers work. – saulspatz Dec 04 '20 at 22:19
2

In python 3, the prefered way is as follows:

  • use f-string (formatted string literal)
  • specify the width (the number after the colon) with a leading zero to indicate that you want zero rather than blank if the number is not larger enough.

For example:

a = 20
print(f"number is {a :03}")

Note that there is no space after the colon, otherwise the leading zero has no effect.

Youjun Hu
  • 991
  • 6
  • 18