73

Say I wanted to display the number 123 with a variable number of padded zeroes on the front.

For example, if I wanted to display it in 5 digits I would have digits = 5 giving me:

00123

If I wanted to display it in 6 digits I would have digits = 6 giving:

000123

How would I do this in Python?

Dave
  • 6,802
  • 7
  • 37
  • 71
Eddy
  • 6,211
  • 20
  • 56
  • 70

7 Answers7

194

If you are using it in a formatted string with the format() method which is preferred over the older style ''% formatting

>>> 'One hundred and twenty three with three leading zeros {0:06}.'.format(123)
'One hundred and twenty three with three leading zeros 000123.'

See
http://docs.python.org/library/stdtypes.html#str.format
http://docs.python.org/library/string.html#formatstrings

Here is an example with variable width

>>> '{num:0{width}}'.format(num=123, width=6)
'000123'

You can even specify the fill char as a variable

>>> '{num:{fill}{width}}'.format(num=123, fill='0', width=6)
'000123'
John La Rooy
  • 281,034
  • 50
  • 354
  • 495
  • 5
    +1 for mentioning the new format method. It's taking a bit to get used to, but I actually feel it's a bit cleaner than the old `%` style, which feels ironic to me because I used to feel that the `%` style was the cleanest method. – Wayne Werner Jul 12 '10 at 13:27
  • 8
    Unnamed placefolders are also supported (at least in Python 3.4): `"{:{}{}}".format(123, 0, 6)`. – CodeManX Aug 23 '15 at 21:01
  • 3
    @CoDEmanX The unnamed placeholders also work in python 2.7 - thanks. – fantabolous Nov 09 '15 at 15:12
  • 6
    With the introduction of f-strings in Python 3.6, it is now possible to access previously defined variables without the need for `.format`. Simply prepend an `f` to the string: `f'{num:{fill}{width}}'`. I added an answer with this info. – joelostblom May 26 '17 at 15:41
41

There is a string method called zfill:

>>> '12344'.zfill(10)
0000012344

It will pad the left side of the string with zeros to make the string length N (10 in this case).

Donald Miner
  • 37,251
  • 7
  • 89
  • 116
  • 1
    This is exactly what I'm looking for, I just do '123'.zfill(m) which allows me to use a variable instead of having a predetermined number of digits. Thanks! – Eddy Jul 12 '10 at 13:32
26
'%0*d' % (5, 123)
Ignacio Vazquez-Abrams
  • 740,318
  • 145
  • 1,296
  • 1,325
  • 1
    This is also quite useful for more general cases. This is the old style of formatting isn't it? It's a shame that the old style is being phased out – Eddy Jul 12 '10 at 13:36
  • What does `*` in `%0*d` mean? I check Python documents. `*` is not in the `format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type]`. – SparkAndShine Sep 23 '16 at 23:12
  • 4
    ["Minimum field width (optional). If specified as an '*' (asterisk), the actual width is read from the next element of the tuple in values, and the object to convert comes after the minimum field width and optional precision."](https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting) – Ignacio Vazquez-Abrams Sep 23 '16 at 23:16
  • @Ignacio Vazquez-Abrams is it possible with new-style formatting also? – user1633361 Apr 03 '20 at 19:34
23

With the introduction of formatted string literals ("f-strings" for short) in Python 3.6, it is now possible to access previously defined variables with a briefer syntax:

>>> name = "Fred"
>>> f"He said his name is {name}."
'He said his name is Fred.'

The examples given by John La Rooy can be written as

In [1]: num=123
   ...: fill='0'
   ...: width=6
   ...: f'{num:{fill}{width}}'

Out[1]: '000123'
joelostblom
  • 35,621
  • 16
  • 134
  • 143
14

For those who want to do the same thing with python 3.6+ and f-Strings this is the solution.

width = 20
py, vg = "Python", "Very Good"
print(f"{py:>{width}s} : {vg:>{width}s}")
Praveen Kulkarni
  • 2,228
  • 1
  • 19
  • 34
5
print "%03d" % (43)

Prints

043

st0le
  • 33,007
  • 8
  • 86
  • 89
1

Use string formatting

print '%(#)03d' % {'#': 2}
002
print '%(#)06d' % {'#': 123}
000123

More info here: link text

Blue Peppers
  • 3,532
  • 2
  • 21
  • 23