Answers:
简单:
>>> import string
>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> import random
>>> random.choice(string.ascii_letters)
'j'
string.ascii_letters
根据当前语言环境返回包含小写字母和大写字母的字符串。
random.choice
从序列中返回单个随机元素。
from string import ascii_letters, digits
和之后from random import choice
):''.join([choice(ascii_letters + digits) for i in range(32)])
>>> import random
>>> import string
>>> random.choice(string.ascii_letters)
'g'
ascii_letters
,ascii_uppercase
,和ascii_lowercase
。
>>>def random_char(y):
return ''.join(random.choice(string.ascii_letters) for x in range(y))
>>>print (random_char(5))
>>>fxkea
生成y个随机字符
''.join(random.sample(string.ascii_lowercase,5))
random.sample()
返回唯一的一组值,这与random.choice()
?不同吗?
random.choice
和random.randint
返回一个值。numpy.random.choice
如果添加replace = False,也可以使用给出唯一的集合,如下所示:numpy.random.choice(string.ascii_lowercase, size=5, replace=False)
完整性的另一种方式:
>>> chr(random.randrange(97, 97 + 26))
利用事实 ascii
“ a”为97,并且字母表中有26个字母。
确定random.randrange()
函数调用的上限和下限时,请记住它random.randrange()
在上限上是互斥的,这意味着它只会生成比提供的值小1个单位的整数。
chr(random.randrange(97, 97 + 26 - 1))
吗?
chr(random.randrange(97, 97 + 26)
。random.randrange()
在上限处是独占的,这意味着为了获得整个字符范围,97 - 122
传递的参数必须为123
。
97 + 26
使用了。
您可以使用它来获得一个或多个随机字母
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']
random.choices
什么?
help(random.choices)
表示,If the relative weights or cumulative weights are not specified, the selections are made with equal probability.
这意味着该分布是离散的均匀分布(en.wikipedia.org/wiki/Discrete_uniform_distribution)。
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())
您可以使用
map(lambda a : chr(a), np.random.randint(low=65, high=90, size=4))
import string
import random
KEY_LEN = 20
def base_str():
return (string.letters+string.digits)
def key_gen():
keylist = [random.choice(base_str()) for i in range(KEY_LEN)]
return ("".join(keylist))
您可以这样获得随机字符串:
g9CtUljUWD9wtk1z07iF
ndPbI1DDn6UvHSQoDMtd
klMFY3pTYNVWsNJ6cs34
Qgr7OEalfhXllcFDGh2l
string.ascii_letters
2.您可以通过使用keylist = random.choices(base_str(), k=KEY_LEN)
3. 保存列表推导。为什么要具有base_str
函数而不是base_str = string.ascii_letters+string.digits
?
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 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))
结果:
我的代码过于复杂:
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')
它基本上会从26个随机数中生成一个,然后转换为相应的字母。可以改进它,但是我只是一个初学者,我为这段代码感到自豪。
print(chr(96 + letter))
,没有if
- elif
到底是需要
在键盘上放一个python,让他翻动字母,直到找到自己喜欢的随机组合。
import string #This was a design above but failed to print. I remodled it.
import random
irandom = random.choice(string.ascii_letters)
print irandom