Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to loop from 0000 to 9999 and convert the number to the relative string?

i want to get some string, range from 0000 to 9999, that's to say, i want to print the following string:

0000
0001
0002
0003
0004
0005
0006
....
9999

i tried to use print "\n".join([str(num) for num in range(0, 9999)]), but failed, i get the following number:

0
1
2
3
4
5
6
...
9999

i want python to add the prefix 0 automatically, making the number remain 4 bit digits all the time. can anyone give a hand to me? any help appreciated.

like image 568
Searene Avatar asked Mar 02 '12 04:03

Searene


2 Answers

One way to get what you want is to use string formatting:

>>> for i in range(10):
...     '{0:04}'.format(i)
... 
'0000'
'0001'
'0002'
'0003'
'0004'
'0005'
'0006'
'0007'
'0008'
'0009'

So to do what you want, do this:

print("\n".join(['{0:04}'.format(num) for num in range(0, 10000)]))
like image 149
senderle Avatar answered Oct 13 '22 02:10

senderle


http://docs.python.org/library/stdtypes.html#str.zfill

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

E.g.:

>>> for i in range(10):
...   print('{:d}'.format(i).zfill(4))
... 
0000
0001
0002
0003
0004
0005
0006
0007
0008
0009
like image 38
mechanical_meat Avatar answered Oct 13 '22 02:10

mechanical_meat