Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 551
pierroz Avatar asked Sep 28 '10 14:09

pierroz


People also ask

How do I format an int to a string 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.

How do you specify a format in Python?

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.

Which function can be used to convert a number into string format?

We can convert numbers to strings through using the str() method.


2 Answers

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

like image 184
nmichaels Avatar answered Sep 27 '22 02:09

nmichaels


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

like image 36
Srikar Appalaraju Avatar answered Sep 23 '22 02:09

Srikar Appalaraju