Reputation: 5072
I need to generate random string in python, that is in range 01 - 12. The zero has to be there in front, if the number is below 10. So basically I need the function to return something like 05 or 09 or 11. Can I do it somehow using the random class? Or do i just define and array which contains those 12 strings and take it from there by random index?
Upvotes: 2
Views: 1550
Reputation: 863
I think the best way is to build the array and using random.choice.
random.choice(['0' + str(i) if i<10 else str(i) for i in range(13)])
Upvotes: 0
Reputation: 304355
>>> import random
>>> "%02d"%random.randrange(1, 13)
'07'
or
>>> format(random.randrange(1, 13), '02')
'06'
or
>>> str(random.randrange(1, 13)).zfill(2)
'12'
or
>>> '000000000111123456789012'[random.randrange(12)::12]
'04'
Upvotes: 7