4

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 ?

Ricardo Altamirano
  • 14,650
  • 21
  • 72
  • 105
Deepankar Bajpeyi
  • 5,661
  • 11
  • 44
  • 64

3 Answers3

14

The usual way is random.choice()

>>> import string
>>> import random
>>> random.choice(string.ascii_letters + string.digits)
'v'
poitroae
  • 21,129
  • 10
  • 63
  • 81
  • 4
    `string.letters` is a bit tricky, because it depends on the locale and is no longer available in Python 3. I would use `string.ascii_letters + string.digits` for OP's use case. – Niklas B. Feb 12 '13 at 12:04
4

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
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
2

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.

Ricardo Altamirano
  • 14,650
  • 21
  • 72
  • 105