[Tutor] Generating random alphanumeric codes
Martin A. Brown
martin at linux-ip.net
Tue Jun 26 21:47:06 CEST 2012
Hello,
: Would anyone have tips on how to generate random 4-digit
: alphanumeric codes in python? Also, how does one calculate the
: number of possible combinations?
Here are some thoughts that come to my mind:
import string
import random
# -- technique #1, using random.choice
print ''.join([random.choice(string.lowercase) for x in range(4)])
# -- technique #2, using random.shuffle
t = [ x for x in string.lowercase ]
random.shuffle(t)
''.join(t[0:4])
# -- technique #3, using random.sample
''.join(random.sample(string.lowercase,4))
I would be quite surprised if there were not more efficient ways of
accomplishing this.
-Martin
--
Martin A. Brown
http://linux-ip.net/
More information about the Tutor
mailing list