在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
python 实现随机生成包8位包含大写字母、小写字母和数字的密码的程序。 import string, random src_upp = string.ascii_uppercase src_let = string.ascii_lowercase src_num = string.digits lis = [] count = input('请输入次数:').strip() # for 循环实现(产生密码数可能不足) for i in range(int(count)): print(i) # 先随机定义3种类型各自的个数(总数为8) upp_c = random.randint(1, 6) low_c = random.randint(1, 8-upp_c - 1) num_c = 8 - (upp_c + low_c) # 随机生成密码 password = random.sample(src_upp, upp_c)+random.sample(src_let, low_c)+random.sample(src_num, num_c) # 打乱列表元素 random.shuffle(password) # 列表转换为字符串 new_password = ''.join(password)+'\n' if new_password not in lis: lis.append(new_password) with open('password.txt', 'w') as fw: fw.seek(0) fw.writelines(lis) fw.close() # while 循环实现(只有密码不重复才+1) j=0 while j< int(count): print(j) upp_c = random.randint(1, 6) low_c = random.randint(1, 8 - upp_c - 1) num_c = 8 - (upp_c + low_c) # 随机生成密码 password = random.sample(src_upp, upp_c) + random.sample(src_let, low_c) + random.sample(src_num, num_c) # 打乱列表元素 random.shuffle(password) # 列表转换为字符串 new_password = ''.join(password) + '\n' if new_password not in lis: lis.append(new_password) j += 1 with open('password.txt', 'w') as fw: fw.seek(0) fw.writelines(lis) fw.close()
# 用集合交集的方法生成密码: import random,string num = input('请输入一个数字:').strip() pwds = set() if num.isdigit(): while len(pwds)<int(num): # 保证生成条数足够 passwd = set(random.sample(string.ascii_letters+string.digits,8)) set1 = set(string.ascii_uppercase).intersection(passwd) set2 = set(string.ascii_lowercase).intersection(passwd) set3 = set(string.digits).intersection(passwd) if set1 and set2 and set3: str_passwd=''.join(passwd)+'\n'#要把产生的密码变成字符串,因为前面已经给变成集合了 pwds.add(str_passwd) fw =open('pwds.txt','w') fw.writelines(pwds) else: print('你输入的不是数字')
生成密码txt文件内容:
|
请发表评论