HomeLanguagesHow to generate a random letter in Python?

How to generate a random letter in Python?

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
RELATED ARTICLES

2 COMMENTS

Most Popular

Dominic
32688 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
7057 POSTS0 COMMENTS
Nicole Veronica
12198 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12293 POSTS0 COMMENTS
Shaida Kate Naidoo
7182 POSTS0 COMMENTS
Ted Musemwa
7447 POSTS0 COMMENTS
Thapelo Manthata
7160 POSTS0 COMMENTS
Umr Jansen
7150 POSTS0 COMMENTS