views:

7566

answers:

4

What is the nicest/shortest way to pad a string with zeroes to the left, so the string length has a specific length?

+6  A: 

For numbers:

print "%05d" % number

See also: Python: String formatting.

EDIT: It's worth noting that as of yesterday, this method of formatting is deprecated in favour of the format string method:

print("{0:05d}".format(number)) # or
print(format(number, "05d"))

See PEP 3101 for details.

Konrad Rudolph
+40  A: 

Strings:

>>> n = '4'
>>> print n.zfill(3)
>>> '004'

And for numbers:

>>> n = 4
>>> print '%03d' % n
>>> '004'
Harley
+3  A: 
width = 10
x = 5
print "%0*d" % (width, x)
> 0000000005

See the print documentation for all the exciting details!

Peter Rowell
+4  A: 

Just use the rjust method of the string object.

This example will make a string of 10 characters long, padding as necessary.

>>> t = 'test'
>>> t.rjust(10, '0')
>>> '000000test'
Paul D. Eden