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