Alex Rivera | Logout

Python Four Digits Counter

Asked 2011-03-10T06:53:38.803
11

How do we use python to generate a four digit counter?

range(0,9999)

will have 1 digits, 2 digits and 3 digits. We only want 4 digits.

i.e. 0000 to 9999

Of course, the simplest Pythonic way.

Edit
Report

2 Answers

22

Format the string to be padded with 0's. To get a list of 0 to 9999 padded with zeroes:

["%04d" % x for x in range(10000)]

Same thing works for 5, 6, 7, 8 zeroes, etc. Note that this will give you a list of strings. There's no way to have an integer variable padded with zeroes, so the string is as close as you can get.

The same format operation works for individual ints as well.

answered 2011-03-10T06:56:12.667
20

Maybe str.zfill could also help you:

>>> "1".zfill(4)
'0001'
answered 2011-03-10T07:45:39.313

Your Answer