Simple:
>>> import string
>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> import random
>>> random.choice(string.ascii_letters)
'j'
string.ascii_letters
returns a string containing the lower case and upper case letters according to the current locale.
random.choice
returns a single, random element from a sequence.
>>> import random
>>> import string
>>> random.choice(string.ascii_letters)
'g'
>>>def random_char(y):
return ''.join(random.choice(string.ascii_letters) for x in range(y))
>>>print (random_char(5))
>>>fxkea
to generate y number of random characters
>>> import random
>>> import string
>>> random.choice(string.ascii_lowercase)
'b'
You can use this to get one or more random letter(s)
import random
import string
random.seed(10)
letters = string.ascii_lowercase
rand_letters = random.choices(letters,k=5) # where k is the number of required rand_letters
print(rand_letters)
['o', 'l', 'p', 'f', 'v']
Another way, for completeness:
>>> chr(random.randrange(97, 97 + 26))
Use the fact that ascii
'a' is 97, and there are 26 letters in the alphabet.
When determining the upper and lower bound of the random.randrange()
function call, remember that random.randrange()
is exclusive on its upper bound, meaning it will only ever generate an integer up to 1 unit less that the provided value.
You can just make a list:
import random
list1=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
b=random.randint(0,7)
print(list1[b])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With