In Python, how to specify a format when converting int to string?

With python3 format and the new 3.6 f"" notation:

>>> i = 5
>>> "{:4n}".format(i)
'   5'
>>> "{:04n}".format(i)
'0005'
>>> f"{i:4n}"
'   5'
>>> f"{i:04n}" 
'0005'

"%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...

Tags:

Python

String