Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

randint with leading zeros

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?

like image 585
Birgit Avatar asked Oct 20 '25 05:10

Birgit


2 Answers

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

number="%05d" % randint(0,99999)
like image 122
KevinDTimm Avatar answered Oct 21 '25 17:10

KevinDTimm


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")
like image 27
kindall Avatar answered Oct 21 '25 17:10

kindall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!