开发者

Python Four Digits Counter

开发者 https://www.devze.com 2023-02-16 11:17 出处:网络
开发者_开发技巧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.
开发者_开发技巧

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.


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.


Maybe str.zfill could also help you:

>>> "1".zfill(4)
'0001'


You don't. You format to 4 digits when outputting or processing.

print '%04d' % val


if you'd like to choose string formatting, as many suggested, and you are using a Python not less than 2.6, take care to use string formatting in its newest incarnation. Instead of:

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

it is suggested to opt for:

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

This is because this latter way is used in Python 3 as default idiom to format strings and I guess it's a good idea to enhance your code portability to future Python versions.

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

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


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

精彩评论

暂无评论...
验证码 换一张
取 消