Generate a random letter in Python


Question

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.

1
122
6/17/2012 1:39:27 PM

Accepted Answer

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.

207
3/4/2019 11:03:29 AM

>>> import random
>>> import string
>>> random.choice(string.ascii_letters)
'g'

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon