Generate a random letter in Python

Kudu picture Kudu · May 13, 2010 · Viewed 253.5k times · Source

Is there a way to generate random letters in Python (like random.randint but for letters)? The range functionality of random.randint would be nice but having a generator that just outputs a random letter would be better than nothing.

Answer

Mark Rushakoff picture Mark Rushakoff · May 13, 2010

Simple:

>>> import string
>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> import random
>>> random.choice(string.ascii_letters)
'j'

string.ascii_letters returns a string containing the lower case and upper case letters according to the current locale.

random.choice returns a single, random element from a sequence.