How to generate a random letter in Python

Here in this tutorial, we learn how to generate a random letter in Python.

The random module is used to shuffle values, generate some random data, etc and here we will see how it can be used to generate a random letter.

Generating random letter

import string, random

all_alphabets = string.ascii_letters

result = random.choice(all_alphabets)

print(result)

Output:

E

In the code written above, we have used two modules string and random from the Python Standard library.

Through the string module, we have imported all the alphabet(lower case and upper case) in the English language using the function ascii_letters and stored it in a variable called ‘all_alphabets’.

Then we used the function choice() in the random module which helped us select a single letter from the given sequence and passed the string ‘all_alphabets’ in it. And in the end, we printed the result.

Thus we have seen how to generate a random letter in Python.

To read more about the choice() function in the random module refer to:

Leave a Reply

Your email address will not be published.