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
2010-05-12 22:51:54
It's actually string.ascii_lowercase or string.ascii_uppercase.
Taylor Leese
2010-05-12 22:54:19
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
2010-05-12 23:12:23
+10
A:
>>> import random
>>> import string
>>> random.choice(string.ascii_letters)
'g'
joaquin
2010-05-12 22:52:59
This can be lower or uppercase. Not sure if that is what is needed.
Taylor Leese
2010-05-12 22:55:54
+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
2010-05-12 22:55:05
+2
A:
>>> import random
>>> import string
>>> random.choice(string.ascii_lowercase)
'b'
Taylor Leese
2010-05-12 22:55:09
+1
A:
def randchar(a, b):
return chr(random.randint(ord(a), ord(b)))
Florian Diesch
2010-05-12 22:58:47