Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Four Digits Counter

Tags:

python

counter

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.

like image 373
LynxLee Avatar asked Mar 10 '11 06:03

LynxLee


2 Answers

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.

like image 124
Rafe Kettler Avatar answered Oct 05 '22 10:10

Rafe Kettler


Maybe str.zfill could also help you:

>>> "1".zfill(4)
'0001'
like image 43
nkint Avatar answered Oct 05 '22 11:10

nkint