我想创建一个00000到99999的数字列表,我想将它保存在一个文件中。但问题是Python删除了前导零,使00000只为0.这是我的代码。
f=open("numbers","w")
x=00000
y=99999
while y>=x:
zzz=str(x)+'\n'
f.write(zzz)
x=x+1
我想保存这些数字:
00000 00001 00002 等等...
我是Python的新手,我将不胜感激任何帮助。感谢。
答案 0 :(得分:4)
只需使用format:
>>> print('{:05}'.format(1))
00001
答案 1 :(得分:3)
第三种可能性是zfill
:
str(x).zfill(5)
答案 2 :(得分:2)
使用'%05d' % x
代替str(x)
。
答案 3 :(得分:0)
x = 000和x = 0以完全相同的方式存储...作为整数零。你想要的是按照你需要的方式打印字符串。这就是你要找的东西:
以下是您要找的内容:
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.