How can I select random characters in a pythonic w

2019-04-10 09:51发布

问题:

This question already has an answer here:

  • Generate a random letter in Python 18 answers

I want to generate a 10 alphanumeric character long string in python . So here is one part of selecting random index from a list of alphanumeric chars.

My plan :

set_list = ['a','b','c' ........] # all the way till I finish [a-zA-Z0-9]

index = random()    # will use python's random generator
some_char = setlist[index]

Is there a better way of choosing a character randomly ?

回答1:

The usual way is random.choice()

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


回答2:

try this:

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

run:

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

if you have a list then you can do like this:

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

if you want to use special symbols , you can use string's punctuation:

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


回答3:

random() isn't 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 contingent on the locale, and was removed in Python 3.



标签: python random