所以我需要生成一個10位密碼(需要使用random模塊),每次必須包含2個小寫字母、2個大寫字母、3個特殊符號和3個數字,所有這些都以隨機順序排列。我已經完成了隨機密碼生成器部分,但我不確定如何將其限制為 2 個小寫字母、2 個大寫字母、3 個特殊符號和 3 個數字。
這是我到目前為止所擁有的:
import random
import string
lc_letter = ["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"]
uc_letter = ["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"]
symbols = ["!","@","#","$","%","^","&","*","(",")","_"," ","=","-","/",">","<",",",".","?","\\"]
numbers = ["0","1","2","3","4","5","6","7","8","9"]
options = [lc_letter,uc_letter,symbols,numbers]
for i in range(10):
choice = random.choice(options)
digit = random.choice(choice)
print(digit, end = '')
uj5u.com熱心網友回復:
我建議的另一種方法是,從大寫、小寫等中取出 2 個字母,然后使用random.shuffle方法對生成的密碼進行洗牌。
uj5u.com熱心網友回復:
首先選擇每個需要的字符,然后將它們洗牌:
from random import choice as rd
from random import shuffle
import string
lc_letter = ["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"]
uc_letter = ["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"]
symbols = ["!","@","#","$","%","^","&","*","(",")","_"," ","=","-","/",">","<",",",".","?","\\"]
numbers = ["0","1","2","3","4","5","6","7","8","9"]
options = [
rd(lc_letter),
rd(lc_letter),
rd(uc_letter),
rd(uc_letter),
rd(symbols),
rd(symbols),
rd(symbols),
rd(numbers),
rd(numbers),
rd(numbers),
]
shuffle(options)
print(''.join(options))
uj5u.com熱心網友回復:
您可以使用以下常量string:
import random
import string
s = ""
for i in range(2):
s = s random.choice(string.ascii_lowercase)
for i in range(2):
s = s random.choice(string.ascii_uppercase)
for i in range(3):
s = s random.choice(string.punctuation)
for i in range(3):
s = s random.choice(string.digits)
s = ''.join(random.sample(s, 10))
print(s)
uj5u.com熱心網友回復:
您可以使用模塊中的random.choice、random.sample和 常量string來獲取隨機生成的密碼。
import random
import string
lc_letter = string.ascii_lowercase
uc_letter = string.ascii_uppercase
# Could use string.punctuation here, but it would be different
# as your list doesn't contain semicolons or colons,
# while string.punctuation does.
symbols = ["!","@","#","$","%","^","&","*","(",")","_"," ","=","-","/",">","<",",",".","?","\\"]
numbers = string.digits
lc_selection = [random.choice(lc_letter) for _ in range(2)]
uc_selection = [random.choice(uc_letter) for _ in range(2)]
symbol_selection = [random.choice(symbols) for _ in range(3)]
number_selection = [random.choice(numbers) for _ in range(3)]
print(''.join(random.sample(lc_selection uc_selection symbol_selection number_selection, 10)))
uj5u.com熱心網友回復:
您實際上可以做的是制作一個長度為 10 的串列,如下所示:
dist = [0, 0, 1, 1, 2, 2, 2, 3, 3, 3]
此串列表示串列中每個索引的分布options。例如,您在選項中將小寫字母放在首位,您必須選擇 2 個小寫值,因此分配串列中有 2 個零。
現在您可以在串列中選擇一個索引:
idx = random.randint(0, len(dist))
然后,從串列中選擇您的選擇:options[dist[idx]]。
最后是frompop的值。idxdist
dist.pop(idx)
這將以相同的概率生成所有有效密碼。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/419905.html
標籤:
