Generate a random letter in Python
This post will discuss how to generate a random letter in Python.
In the previous post, we have discussed how to generate a random number in Python. This post provides an overview of several functions to generate a random letter in Python.
1. Using random.choice() function
The random.choice() function is used to pick a random item from the specified sequence. The idea is to use the ascii_letters constant from the string module, which returns a string containing the ranges A-Za-z, i.e., lowercase and uppercase letters.
|
1 2 3 4 5 6 7 |
import string, random if __name__ == '__main__': rand = random.choice(string.ascii_letters) print(rand) |
2. Using secrets.choice() function
If you need to generate a cryptographically secure random letter, consider using the choice() function from the secrets module.
|
1 2 3 4 5 6 7 |
import string, secrets if __name__ == '__main__': rand = secrets.choice(string.ascii_letters) print(rand) |
3. Using random.randint() function
The random.randint(x, y) function generates the random integer n such that x <= n <= y. If you need to generate a random letter, you can do like:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import random # generate a random letter in the range x - y def randletter(x, y): return chr(random.randint(ord(x), ord(y))) if __name__ == '__main__': # generate a random letter in the range `a-z` r = randletter('a', 'z') # generate a random letter in the range `A-Z` R = randletter('A', 'Z') # randomly pick the letter `r` or `R` rand = (r, R)[random.randint(0, 1)] print(rand) |
That’s all about generating a random letter in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)