views:

72

answers:

4

More precisely, I want my format to add leading zeros to have string with constant length.
e.g. 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?

+5  A: 

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

You can read about string formatting here.

Nathon
so easy :) excellent thx
PierrOz
+3  A: 

You could use the zfill function of str class. Eg: str(165).zfill(4).

This would give - '0165'

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

MovieYoda
A: 

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
A: 

Try formatted string printing:

print "%04d" % 1 Outputs 0001

Powertieke