Python Four Digit Counter

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

range(0,9999) 

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

i.e. 0000 - 9999

Of course, the easiest Python path.

+4
source share
5 answers

Format a string filled with zeros. To get a list from 0 to 9999 with zeros:

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

The same thing works for 5, 6, 7, 8 zeros, etc. Please note that this will give you a list of strings. There is no way to have an integer variable padded with zeros, so the string should be as close as possible.

The same formatting operation also works for individual ints.

+10
source

Maybe str.zfill can also help you:

 >>> "1".zfill(4) '0001' 
+11
source

No. When outputting or processing, you format up to 4 digits.

 print '%04d' % val 
+4
source

if you want to choose string formatting, like many of the suggested ones, and you are using Python at least 2.6, take care of string formatting in your newest incarnation. Instead:

 ["%04d" % idx for idx in xrange(10000)] 

It is suggested to choose:

 ["{0:0>4}".format(i) for i in xrange(1000)] 

This is because the latter method is used in Python 3 as a standard idiom for formatting strings, and I think it is a good idea to increase code portability for future versions of Python.

As someone said in the comments, in Python 2.7+ there is no need to specify a positional argument, so this is also true:

 ["{:0>4}".format(i) for i in xrange(1000)] 
+1
source

And to really go overboard,

 In [8]: class Int(int): ...: def __repr__(self): ...: return self.__str__().zfill(4) ...: ...: In [9]: a = Int(5) In [10]: a Out[10]: 0005 
0
source

Source: https://habr.com/ru/post/1343127/


All Articles