Add leading Zero Python

Question:

I was wondering if someone could help me add a leading zero to this existing string when the digits are sings (eg 1-9). Here is the string:

str(int(length)/1440/60)
Asked By: Evan Gervais

||

Answers:

You can use the builtin str.zfill method, like this

my_string = "1"
print my_string.zfill(2)   # Prints 01

my_string = "1000"
print my_string.zfill(2)   # Prints 1000

From the docs,

Return the numeric string left filled with zeros in a string of length
width. A sign prefix is handled correctly. The original string is
returned if width is less than or equal to len(s).

So, if the actual string’s length is more than the width specified (parameter passed to zfill) the string is returned as it is.

Answered By: thefourtheye

I hope this is the easiest way:

 >>> for i in range(1,15):
 ...     print '%0.2d' % i
 ...
 01
 02
 03
 04
 05
 06
 07
 08
 09     
 10
 11
 12
 13
 14
 >>>
Answered By: James

Using format or str.format, you don’t need to convert the number to str:

>>> format(1, '02')
'01'
>>> format(100, '02')
'100'

>>> '{:02}'.format(1)
'01'
>>> '{:02}'.format(100)
'100'

According to the str.format documentation:

This method of string formatting is the new standard in Python 3, and
should be preferred to the % formatting …

Answered By: falsetru
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.