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?
With python3 format notation:
You could use the
zfill
function ofstr
class. Like so -One could also do
%04d
etc. like the others have suggested. But I thought this is more pythonic way of doing this..."%04d"
where the 4 is the constant length will do what you described.You can read about string formatting here.
Try formatted string printing:
print "%04d" % 1
Outputs 0001Use the percentage (
%
) operator:Documentation is over here
The advantage in using
%
instead of zfill() is that you parse values into a string in a more legible way: