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

Viewed 54107

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?

5 Answers

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'
Related