Search code examples
pythonrandompython-3.x

Generate a random letter in Python


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.


Solution

  • 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.