views:

326

answers:

5

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.

+8  A: 

Simple:

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

string.letters returns a string containing the lower case and upper case letters according to the current locale; if that's not acceptable, string.ascii_letters will probably do the trick.

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

Mark Rushakoff
It's actually string.ascii_lowercase or string.ascii_uppercase.
Taylor Leese
string.letters disappeared after python 2.6. In python 3.1 you must use string.ascii_letters that is also present in python 2.6
joaquin
+10  A: 
>>> import random
>>> import string
>>> random.choice(string.ascii_letters)
'g'
joaquin
This can be lower or uppercase. Not sure if that is what is needed.
Taylor Leese
+1  A: 

Another way, for completeness:

>>> chr(random.randrange(97, 97 + 26 + 1))

Use the fact that ascii 'a' is 97, and there are 26 letters in the alphabet.

rlotun
That depends on what alphabet we're talking about ;-)
Joey
+2  A: 
>>> import random
>>> import string    
>>> random.choice(string.ascii_lowercase)
'b'
Taylor Leese
+1  A: 
def randchar(a, b):
    return chr(random.randint(ord(a), ord(b)))
Florian Diesch