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:
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?
To convert an integer to string in Python, use the str() function. This function takes any data type and converts it into a string, including integers. Use the syntax print(str(INT)) to return the int as a str , or string.
The format() method formats the specified value(s) and insert them inside the string's placeholder. The placeholder is defined using curly brackets: {}. Read more about the placeholders in the Placeholder section below. The format() method returns the formatted string.
We can convert numbers to strings through using the str() method.
"%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 the str.format
method or format
builtin function. See the format specification mini-language documentation.
You could use the zfill
function of str
class. Like so -
>>> str(165).zfill(4) '0165'
One could also do %04d
etc. like the others have suggested. But I thought this is more pythonic way of doing this...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With