How to execute a cycle from 0000 to 9999 and convert a number to a relative string?

I want to get a line, a range from 0000 to 9999, that I want to print the following line:

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

I tried using print "\n".join([str(num) for num in range(0, 9999)]) but couldn’t, I got the following number:

 0 1 2 3 4 5 6 ... 9999 

I want python to automatically add the prefix 0 , leaving the number of 4-bit digits all the time. can anyone give me a hand? any help was appreciated.

+4
source share
5 answers

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

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

To do what you want, do the following:

 print "\n".join(['{0:04}'.format(num) for num in xrange(0, 10000)]) 
+15
source

try it

 print"\n".join(["%#04d" % num for num in range(0, 9999)]) 
+5
source

Just using str.rjust :

 print "\n".join([str(num).rjust(4, '0') for num in range(0, 1000)]) 

Return the string that will be correctly defined in the length width string. stuffing is performed using the specified fillchar (the default is ASCII space). the original string is returned if the width is less than or equal to len (s).

+5
source

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

Returns a numeric string filled with zeros in a string of length width. The sign prefix is ​​processed correctly. The original string if the width is less than or equal to len (s).

eg:.

 >>> for i in range(10): ... print('{:d}'.format(i).zfill(4)) ... 0000 0001 0002 0003 0004 0005 0006 0007 0008 0009 
+5
source

str.zfill also works:

print('\n'.join([str(num).zfill(4) for num in range(0, 10000)]))

+2
source

Source: https://habr.com/ru/post/1399312/


All Articles