Erki M.
Erki M.

Reputation: 5072

python, generate random string in range 01-12

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

Answers (4)

idog
idog

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

John La Rooy
John La Rooy

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

Dominic Rodger
Dominic Rodger

Reputation: 99801

from random import randint
print '%02d' % randint(1, 12)

Upvotes: 1

jamylak
jamylak

Reputation: 133624

>>> import random
>>> format(random.randint(1, 12), '02')
'07'

Upvotes: 5

Related Questions