16
votes

I wanted to generate numbers starting from 000 to 120 in sequence. I know you can generate numbers from 0 to 120 by using a loop.But I want all the numbers to have 3 digits.

The output should be

000
001
002 
...
...
120

Instead of

0
1
2
...
...
120

Is there any easy way to achieve this in python or should I be making separate code for 0-9 10-99 and 100-120 ?

3
Please show us the code you've tried. - mishik
Codes are usually strings. You can't have a decimal like 001, it will be considered an octal. - Christian
Just in case: print("{:03}".format(x)) - mishik

3 Answers

39
votes
["{0:03}".format(i) for i in range(121)]

or

["%03d" % i for i in range(121)]

To print:

print "\n".join(<either of the above expressions>)

More terse in Python 3.6+:

[f"{i:03}" for i in range(121)]
3
votes

python 3.6

for i in range(121):
    print(f'{i:03}')
2
votes
print [format(item, "03d") for item in xrange(121)]