Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

How to generate a random letter in Python?

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

In this article, let’s discuss how to generate a random letter. Python provides rich module support and some of these modules can help us to generate random numbers and letters. There are multiple ways we can do that using various Python modules.

Generate a random letter using a string and a random module

The string module has a special function ascii_letters which returns a string containing all the alphabets from a-z and A-Z, i.e. all the lowercase and uppercase alphabets. Using random.choice() we can choose any of the particular characters from that string.

Python3




# Import string and random module
import string
import random
 
# Randomly choose a letter from all the ascii_letters
randomLetter = random.choice(string.ascii_letters)
print(randomLetter)

Output:

w

Generate a random letter using the only random module

Using random.randint(x,y) we can generate random integers from x to y. So we can randomly generate the ASCII value of one of the alphabets and then typecast them to char using chr() function

Python3




# Import string and random module
import random
 
# Randomly generate a ascii value
# from 'a' to 'z' and 'A' to 'Z'
randomLowerLetter = chr(random.randint(ord('a'), ord('z')))
randomUpperLetter = chr(random.randint(ord('A'), ord('Z')))
print(randomLowerLetter, randomUpperLetter)

Output:

n M
My Personal Notes arrow_drop_up
Last Updated : 08 Sep, 2022
Like Article
Save Article
Similar Reads
Related Tutorials