0

I want to create a list of numbers from 00000 to 99999, and I want to save it in a file. But the problem is that Python removes the leading zeroes, making 00000 just 0. Here's my code.

f=open("numbers","w")
x=00000
y=99999
while y>=x:
    zzz=str(x)+'\n'
    f.write(zzz)
    x=x+1

I want to save these numbers like this:

00000 00001 00002 And so on...

I am new to Python and I would appreciate any help. Thanks.

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
dabougeoise
  • 1
  • 1
  • 1
  • check out this post http://stackoverflow.com/questions/2389846/python-decimals-format – LWZ Feb 24 '13 at 07:20
  • 1
    Leading zeros are insignificant to a *number*: `0` = `000` = `00000` even though they have different *textual* representations. Check the duplicate question(s). (Sometimes a leading zero indicates octal, but that is tangental.) –  Feb 24 '13 at 07:27

4 Answers4

4

Just use format:

>>> print('{:05}'.format(1))
00001
dawg
  • 98,345
  • 23
  • 131
  • 206
3

The third possibility is zfill:

str(x).zfill(5)
agf
  • 171,228
  • 44
  • 289
  • 238
2

Use '%05d' % x instead of str(x).

Keith Randall
  • 22,985
  • 2
  • 35
  • 54
0

x=000 and x=0 are stored exactly the same way...as the integer zero. What you want is to print strings formatted the way you require. Here's what you are looking for:

Here's what you are looking for:

with open('numbers','w') as f:          # open a file (automatically closes)
    for x in range(10000):              # x = 0 to 9999
        f.write('{:05}\n'.format(x))    # write as a string field formatted as width 5 and leading zeros, and a newline character.
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251