有没有办法让python用这样的数字打印数字
no = ["1", "2", "3", "99", "999"]
print no
并按照这样打印
001, 002, 003, 099, 999
实际上是对于带有数字编号
的打印文本文件名openFile = 'D:/Workspace/python.txt'
savePlace = 'D:/Workspace/python{}.txt'
with open(openFile, 'rb') as inf:
for index, line in enumerate(inf,start=0):
with open(savePlace.format(index) ,'w') as outf:
....
输出D:/工作区
python001.txt
python002.txt
python003.txt
python099.txt
python999.txt
答案 0 :(得分:2)
是的,最简单的方法是zfill(3)。对于您的情况,您将执行以下操作:
no = ["1", "2", "3", "99", "999"]
out = [i.zfill(3) for i in no]
然后你可以用任何方式修改文件。
答案 1 :(得分:2)
您可以使用str.format()。
str.zfill()也可以。但str.format()
是更强大的方法。
>>> ["{:0>3}".format(x) for x in no]
['001', '002', '003', '099', '999']
答案 2 :(得分:1)
虽然其他答案都是正确的,您可以使用zfill
,但您也可以通过更改格式字符串来获得相同的结果
savePlace = 'D:/Workspace/python{}.txt'
到
savePlace = 'D:/Workspace/python{0:03d}.txt'
并保留其余代码。
答案 3 :(得分:0)
[x.zfill(3) for x in no]
你可以使用它。