48

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)
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
Evan Gervais
  • 499
  • 1
  • 4
  • 8
  • 1
    How many leading zeros? – thefourtheye Feb 07 '14 at 06:15
  • 1
    just one. so the digits would be 01, 02, etc. – Evan Gervais Feb 07 '14 at 06:16
  • 1
    // , This isn't a duplicate, since this refers to actually changing the variable's value, not just displaying it differently. The difference is important, since only some of the answers at http://stackoverflow.com/questions/134934/display-number-with-leading-zeros would meet this need. – Nathan Basanese Jan 15 '16 at 23:14

3 Answers3

90

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.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • so nice. if u need a trailing 0 only for single digit numbers str.zfill() will just add to those who actually are singe digits. 7 becomes 07, but 10 would stay 10 and not become 010, for example. – Ulf Gjerdingen Nov 05 '21 at 11:16
27

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

falsetru
  • 357,413
  • 63
  • 732
  • 636
16

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
 >>>
James Sapam
  • 16,036
  • 12
  • 50
  • 73