How to generate a random letter in Python?
Last Updated :
08 Sep, 2022
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
import random
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 random
randomLowerLetter = chr (random.randint( ord ( 'a' ), ord ( 'z' )))
randomUpperLetter = chr (random.randint( ord ( 'A' ), ord ( 'Z' )))
print (randomLowerLetter, randomUpperLetter)
|
Output:
n M
Share your thoughts in the comments
Please Login to comment...