3

I want to generate numbers from 00000 to 99999.

with

number=randint(0,99999)

I only generate values without leading zero's, of course, a 23 instead of a 00023. Is there a trick to generate always 5 digit-values in the sense of %05d or do I really need to play a python-string-trick to fill the missing 0s at front in case len() < 5?

Thanks for reading and helping,

B

Birgit
  • 31
  • 1
  • 2

5 Answers5

10

You will have to do a python-string-trick since an integer, per se, does not have leading zeroes

number="%05d" % randint(0,99999)
KevinDTimm
  • 14,226
  • 3
  • 42
  • 60
3

The numbers generated by randint are integers. Integers are integers and will be printed without leading zeroes.

If you want a string representation, which can have leading zeroes, try:

str(randint(0, 99999)).rjust(5, "0")
kindall
  • 178,883
  • 35
  • 278
  • 309
1

Alternatively, str(randint(0, 99999)).zfill(5), which provides slightly better performance than string formatting (20%) and str.rjust (1%).

Overmind Jiang
  • 623
  • 5
  • 17
0

randint generates integers. Those are simple numbers without any inherent visual representation. The leading zeros would only be visible if you create strings from those numbers (and thus another representation).

Thus, you you have to use a strung function to have leading zeros (and have to deal with those strings later on). E.g. it's not possible to do any calculations afterwards. To create these strings you can do something like

number = "%05d" % random.randint(0,99999)

The gist of all that is that an integer is not the same as a string, even if they look similar.

>>> '12345' == 12345
False
Holger Just
  • 52,918
  • 14
  • 115
  • 123
0

For python, you're generating a bunch of numbers, only when you print it / display it is it converted to string and thus, it can have padding.

You can as well store your number as a formatted string:

 number="%05d" % random.randint(0,9999)
Bruce
  • 7,094
  • 1
  • 25
  • 42