Fork me on GitHub

一 概念
 
密码生成不复杂,可是它却涉及到了string的常用技巧和一些概念
记得python中的random模块,这是所有随机数的藏身之处
记得python中的string模块,这个是字符操作的盛殿堂
 
二 实例解析
 
实例A:
 
这里重点熟悉了random的用法
import random
import math

alpha = "abcdefghijklmnopqrstuvwxyz"
num = "0123456789"
special = "@#$%&*"

pass_len = int(input("Enter password length:"))


alpha_len = pass_len//2
num_len = math.ceil(pass_len*30/100)
special_len = pass_len - (alpha_len+num_len)

password = []

def generate_pass(length,array,is_alpha=False):
    for i in range(length):
        index = random.randint(0,len(array)-1)
        character = array[index]
        if is_alpha:
            case = random.randint(0,1)
            if case == 1:
                character = character.upper()

        password.append(character)


generate_pass(alpha_len,alpha,True)

generate_pass(num_len,num)

generate_pass(special_len,special)

random.shuffle(password)

gen_password = ""

for i in password:
    gen_password = gen_password + str(i)

print(gen_password)

 

 
实例B:
 
这里看一下string的用法,怎么寻找字符,怎么寻找数字,怎么寻找特殊字符
 
 
 
import random
import string

total = string.ascii_letters + string.digits + string.punctuation

length = 16

password = "".join(random.sample(total,length))

print(password)

 

posted on 2022-04-28 17:03  虚生  阅读(85)  评论(0编辑  收藏  举报