Fix Python – Generate a random letter in Python

Question

Asked By – Kudu

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.

Now we will see solution for issue: Generate a random letter in Python


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.

This question is answered By – Mark Rushakoff

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0