24

In Python, how do I specify a format when converting int to string?

More precisely, I want my format to add leading zeros to have a string with constant length. For example, if the constant length is set to 4:

  • 1 would be converted into "0001"
  • 12 would be converted into "0012"
  • 165 would be converted into "0165"

I have no constraint on the behaviour when the integer is greater than what can allow the given length (9999 in my example).

How can I do that in Python?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
pierroz
  • 7,653
  • 9
  • 48
  • 60
  • 6
    Possible duplicate of: [Best way to format integer as string with leading zeros?](http://stackoverflow.com/q/733454/64633) – Rod Sep 28 '10 at 14:25

5 Answers5

26

"%04d" where the 4 is the constant length will do what you described.

You can read about string formatting here.

Update for Python 3:

{:04d} is the equivalent for strings using the str.format method or format builtin function. See the format specification mini-language documentation.

nmichaels
  • 49,466
  • 12
  • 107
  • 135
21

You could use the zfill function of str class. Like so -

>>> str(165).zfill(4)
'0165'

One could also do %04d etc. like the others have suggested. But I thought this is more pythonic way of doing this...

Srikar Appalaraju
  • 71,928
  • 54
  • 216
  • 264
8

With python3 format and the new 3.6 formatted string literals f"":

>>> i = 5
>>> "{:4n}".format(i)
'   5'
>>> "{:04n}".format(i)
'0005'
>>> f"{i:4n}"
'   5'
>>> f"{i:04n}" 
'0005'
NKSM
  • 5,422
  • 4
  • 25
  • 38
MortenB
  • 2,749
  • 1
  • 31
  • 35
5

Try formatted string printing:

print "%04d" % 1 Outputs 0001

Powertieke
  • 2,368
  • 1
  • 14
  • 21
4

Use the percentage (%) operator:

>>> number = 1
>>> print("%04d") % number
0001
>>> number = 342
>>> print("%04d") % number
0342

Documentation is over here

The advantage in using % instead of zfill() is that you parse values into a string in a more legible way:

>>> number = 99
>>> print("My number is %04d to which I can add 1 and get %04d") % (number, number+1)
My number is 0099 to which I can add 1 and get 0100
mac
  • 42,153
  • 26
  • 121
  • 131