Python Four Digits Counter

LynxLee picture LynxLee · Mar 10, 2011 · Viewed 17.3k times · Source

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.

Answer

Rafe Kettler picture Rafe Kettler · Mar 10, 2011

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.