How to choose random characters at the pythonic level?

I want to generate 10 alphanumeric characters of a long string in python. So, here is one part of choosing a random index from a list of alphanumeric characters.

My plan :

set_list = ['a','b','c' ........] # all the way till I finish [a-zA-Z0-9] index = random() # will use python random generator some_char = setlist[index] 

Is there a better way to select a character randomly?

+4
source share
3 answers

The usual way is random.choice ()

 >>> import string >>> import random >>> random.choice(string.ascii_letters + string.digits) 'v' 
+11
source

try the following:

 def getCode(length = 10, char = string.ascii_uppercase + string.digits + string.ascii_lowercase ): return ''.join(random.choice( char) for x in range(length)) 

mileage:

 >>> import random >>> import string >>> getCode() '1RZLCRBBm5' >>> getCode(5, "mychars") 'ahssh' 

if you have a list, you can do it like this:

 >>> set_list = ['a','b','c','d'] >>> getCode(2, ''.join(set_list)) 'da' 

if you want to use special characters, you can use string punctuation:

 >>> print string.punctuation !"#$%&'()*+,-./:;<=> ?@ [\]^_`{|}~ 
+4
source

random() not a function on its own. The traditional way in Python 3 would be:

 import random import string random.choice(string.ascii_letters + string.digits) 

string.letters is locale dependent and is removed in Python 3.

+2
source

All Articles