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

久未见 提交于 2019-11-29 07:48:04

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

try this

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

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

Simply using str.rjust:

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

Return the string right justified in a string of length width. Padding is done using the specified fillchar (default is an ASCII space). The original string is returned if width is less than or equal to len(s).

str.zfill also works:

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

another way to do that:

["%.4d" % i for i in range(0,999)]

or

["%04d" % i for i in range(0,999)]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!