stevanus giri
stevanus giri

Reputation: 51

print number in some digits in python

Is there a way for python to print number with digits like this

no = ["1", "2", "3", "99", "999"]

print no

and it print like this

001, 002, 003, 099, 999

actually for print textfile names with digit number

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

output in D:/Workspace

python001.txt
python002.txt
python003.txt
python099.txt
python999.txt

Upvotes: 1

Views: 535

Answers (4)

Puffin GDI
Puffin GDI

Reputation: 1702

You can use str.format().

str.zfill() also can do. But str.format() is more powerful method.

>>> ["{:0>3}".format(x) for x in no]
['001', '002', '003', '099', '999']

Upvotes: 2

Carsten
Carsten

Reputation: 18446

While the other answers are correct and you can use zfill, you can also achieve the same result by changing your format string

savePlace = 'D:/Workspace/python{}.txt'

to

savePlace = 'D:/Workspace/python{0:03d}.txt'

and leaving the rest of your code as it is.

Upvotes: 1

vks
vks

Reputation: 67968

[x.zfill(3) for x in no]

You can use this.

Upvotes: 0

Salvador Dali
Salvador Dali

Reputation: 222471

Yes, the easiest way would be zfill(3). For your case you will do something like this:

no = ["1", "2", "3", "99", "999"]
out = [i.zfill(3) for i in no]

Then you can modify it in whatever way to do your thing with files.

Upvotes: 2

Related Questions