Is there a way to generate random letters in Python (like random.randint but for letters)? The range functionality of random.randint would be nice but having a generator that just outputs a random letter would be better than nothing.
回答 0
简单:
>>>import string
>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'>>>import random
>>> random.choice(string.ascii_letters)'j'
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.
回答 5
您可以使用它来获得一个或多个随机字母
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_lettersprint(rand_letters)['o','l','p','f','v']
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']
回答 6
您可以列出一个清单:
import random
list1=['a','b','c','d','e','f','g','h']
b=random.randint(0,7)print(list1[b])
import random
def guess_letter():
return random.choice('abcdefghijklmnopqrstuvwxyz')
回答 9
import random
defRandom_Alpha():
l =['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']return l[random.randint(0,25)]print(Random_Alpha())
import random
def Random_Alpha():
l = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
return l[random.randint(0,25)]
print(Random_Alpha())
回答 10
您可以使用
map(lambda a : chr(a), np.random.randint(low=65, high=90, size=4))
map(lambda a : chr(a), np.random.randint(low=65, high=90, size=4))
回答 11
import string
import random
KEY_LEN =20def base_str():return(string.letters+string.digits)def key_gen():
keylist =[random.choice(base_str())for i in range(KEY_LEN)]return("".join(keylist))
def create_key(key_len):
key = ''
valid_characters_list = string.letters + string.digits
for i in range(key_len):
character = choice(valid_characters_list)
key = key + character
return key
def create_key_list(key_num):
keys = []
for i in range(key_num):
key = create_key(key_len)
if key not in keys:
keys.append(key)
return keys
import string
import random
import sys
#make sure it's 3.7 or aboveprint(sys.version)def create_str(str_length):return random.sample(string.ascii_letters, str_length)def create_num(num_length):
digits =[]for i in range(num_length):
digits.append(str(random.randint(1,100)))return digits
def create_special_chars(special_length):
stringSpecial =[]for i in range(special_length):
stringSpecial.append(random.choice('!$%&()*+,-.:;<=>?@[]^_`{|}~'))return stringSpecial
print("how many characters would you like to use ? (DO NOT USE LESS THAN 8)")
str_cnt = input()print("how many digits would you like to use ? (DO NOT USE LESS THAN 2)")
num_cnt = input()print("how many special characters would you like to use ? (DO NOT USE LESS THAN 1)")
s_chars_cnt = input()
password_values = create_str(int(str_cnt))+create_num(int(num_cnt))+ create_special_chars(int(s_chars_cnt))#shuffle/mix the values
random.shuffle(password_values)print("generated password is: ")print(''.join(password_values))
All previous answers are correct, if you are looking for random characters of various types (i.e. alphanumeric and special characters) then here is an script that I created to demonstrate various types of creating random functions, it has three functions one for numbers, alpha- characters and special characters. The script simply generates passwords and is just an example to demonstrate various ways of generating random characters.
import string
import random
import sys
#make sure it's 3.7 or above
print(sys.version)
def create_str(str_length):
return random.sample(string.ascii_letters, str_length)
def create_num(num_length):
digits = []
for i in range(num_length):
digits.append(str(random.randint(1, 100)))
return digits
def create_special_chars(special_length):
stringSpecial = []
for i in range(special_length):
stringSpecial.append(random.choice('!$%&()*+,-.:;<=>?@[]^_`{|}~'))
return stringSpecial
print("how many characters would you like to use ? (DO NOT USE LESS THAN 8)")
str_cnt = input()
print("how many digits would you like to use ? (DO NOT USE LESS THAN 2)")
num_cnt = input()
print("how many special characters would you like to use ? (DO NOT USE LESS THAN 1)")
s_chars_cnt = input()
password_values = create_str(int(str_cnt)) +create_num(int(num_cnt)) + create_special_chars(int(s_chars_cnt))
#shuffle/mix the values
random.shuffle(password_values)
print("generated password is: ")
print(''.join(password_values))
Result:
回答 14
好吧,这就是我的答案!它运作良好。只需将所需的随机字母数放入“数字” …(Python 3)
import random
def key_gen():
keylist = random.choice('abcdefghijklmnopqrstuvwxyz')return keylist
number =0
list_item =''while number <20:
number = number +1
list_item = list_item + key_gen()print(list_item)
well, this is my answer! It works well. Just put the number of random letters you want in ‘number’… (Python 3)
import random
def key_gen():
keylist = random.choice('abcdefghijklmnopqrstuvwxyz')
return keylist
number = 0
list_item = ''
while number < 20:
number = number + 1
list_item = list_item + key_gen()
print(list_item)
回答 15
import string
import random
def random_char(y):return''.join(random.choice(string.ascii_letters+string.digits+li)for x in range(y))
no=int(input("Enter the number of character for your password= "))
li = random.choice('!@#$%^*&( )_+}{')print(random_char(no)+li)
import string
import random
def random_char(y):
return ''.join(random.choice(string.ascii_letters+string.digits+li) for x in range(y))
no=int(input("Enter the number of character for your password= "))
li = random.choice('!@#$%^*&( )_+}{')
print(random_char(no)+li)
回答 16
我的代码过于复杂:
import random
letter =(random.randint(1,26))if letter ==1:print('a')elif letter ==2:print('b')elif letter ==3:print('c')elif letter ==4:print('d')elif letter ==5:print('e')elif letter ==6:print('f')elif letter ==7:print('g')elif letter ==8:print('h')elif letter ==9:print('i')elif letter ==10:print('j')elif letter ==11:print('k')elif letter ==12:print('l')elif letter ==13:print('m')elif letter ==14:print('n')elif letter ==15:print('o')elif letter ==16:print('p')elif letter ==17:print('q')elif letter ==18:print('r')elif letter ==19:print('s')elif letter ==20:print('t')elif letter ==21:print('u')elif letter ==22:print('v')elif letter ==23:print('w')elif letter ==24:print('x')elif letter ==25:print('y')elif letter ==26:print('z')
import random
letter = (random.randint(1,26))
if letter == 1:
print ('a')
elif letter == 2:
print ('b')
elif letter == 3:
print ('c')
elif letter == 4:
print ('d')
elif letter == 5:
print ('e')
elif letter == 6:
print ('f')
elif letter == 7:
print ('g')
elif letter == 8:
print ('h')
elif letter == 9:
print ('i')
elif letter == 10:
print ('j')
elif letter == 11:
print ('k')
elif letter == 12:
print ('l')
elif letter == 13:
print ('m')
elif letter == 14:
print ('n')
elif letter == 15:
print ('o')
elif letter == 16:
print ('p')
elif letter == 17:
print ('q')
elif letter == 18:
print ('r')
elif letter == 19:
print ('s')
elif letter == 20:
print ('t')
elif letter == 21:
print ('u')
elif letter == 22:
print ('v')
elif letter == 23:
print ('w')
elif letter == 24:
print ('x')
elif letter == 25:
print ('y')
elif letter == 26:
print ('z')
It basically generates a random number out of 26 and then converts into its corresponding letter. This could defiantly be improved but I am only a beginner and I am proud of this piece of code.
回答 17
也许这可以帮助您:
import random
for a in range(64,90):
h = random.randint(64, a)
e += chr(h)print e