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?
"%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 thestr.formatmethod orformatbuiltin function. See the format specification mini-language documentation.