Python生成随机密码

一、生成随机密码要实现的功能:

1、输入次数,输入多少次就产生多少条数据

2、要求密码必须包含大写字母、小写字母和数字,长度8位,不能重复

 

二、实现代码

import random,string
src = string.ascii_letters + string.digits
count = input('请确认要生成几条密码: ')
list_passwds = []
for i in range(int(count)):
    list_passwd_all = random.sample(src, 5) #从字母和数字中随机取5位
    list_passwd_all.extend(random.sample(string.digits, 1))  #让密码中一定包含数字
    list_passwd_all.extend(random.sample(string.ascii_lowercase, 1)) #让密码中一定包含小写字母
    list_passwd_all.extend(random.sample(string.ascii_uppercase, 1)) #让密码中一定包含大写字母
    random.shuffle(list_passwd_all) #打乱列表顺序
    str_passwd = ''.join(list_passwd_all) #将列表转化为字符串
    if str_passwd not in list_passwds: #判断是否生成重复密码
        list_passwds.append(str_passwd)
print(list_passwds)

 

三、利用集合的交运算实现

import random,string
passwds = []  #保存符合要求的密码
count = input('请确认要生成几条密码: ')
i = 0  #记录符合要求的密码个数
while i < int(count):
    passwd = set(random.sample(string.ascii_letters + string.digits,8)) #从字母和数字中随机抽取8位生成密码
    if passwd.intersection(string.ascii_uppercase) and passwd.intersection(string.ascii_lowercase) and passwd.intersection(string.digits): #判断密码中是否包含大小写字母和数字
        passwds.append(''.join(passwd))  #将集合转化为字符串
        i += 1 #每生成1个符合要求的密码,i加1
print(passwds)

 

四、利用正则表达式实现

import re, random, string

count1 = int(input('请输入密码个数(必须大于0): '))
i = 0
passwds = []
while i < count1:
    tmp = random.sample(string.ascii_letters + string.digits, 8)
    passwd = ''.join(tmp)
    if re.search('[0-9]', passwd) and re.search('[A-Z]', passwd) and re.search('[a-z]', passwd):
        passwds.append(passwd)
        i += 1
print(passwds)

 

   

转载于:https://www.cnblogs.com/jessicaxu/p/7656763.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值