源码如下:
#-*-coding:utf-8 -*-
#author:wangxing
#description:生成包含大小写字母,数字,特殊字符的随机字符串
import random
import string
import sys
#存储大小写字母和数字,特殊字符列表
STR = [chr(i) for i in range(65,91)] #65-91对应字符A-Z
str = [chr(i) for i in range(97,123)] #a-z
number = [chr(i) for i in range(48,58)] #0-9
#特殊字符串列表获取有点不同
initspecial = string.punctuation #这个函数获取到全部特殊字符,结果为字符串形式
special = [] #定义一个空列表
#制作特殊符号列表
for i in initspecial:
special.append(i)
#生成随机字符串
def Createpassword(total,number1=6):
random_strs = []
while True:
for i in range(number1):
st = random.choice(total)
random_strs.append(st)
# print(st)
random_strs1 = ''.join(random_strs)
return random_strs1
#主程序
if __name__ == '__main__':
tdic = {'1':number,'2':str,'3':STR,'4':str + STR,'5':str + STR + number,'6':number + str,'7':number + STR,'8':str + STR + number + special}
print('****************************')
print('''
*1、纯数字;
*2、纯小写字母;
*3、纯大写字母;
*4、大小写字母混合;
*5、数字大小写字母混合;
*6、数字小写字母混合;
*7、数字大写字母混合;
*8、包含特殊字符;
*q、按q退出。''')
t = input('***请选择类型(输入数字后摁两下空格):')
print('
')
while True:
if t.strip() in ['1', '2', '3', '4', '5', '6', '7', '8']:
t1 = tdic[t]
nl = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
print('******************************')
choices = input("请输入你要得到随机密码的位数与个数(用空格分开,开头为YX):
")
try:
lengths = choices.split(' ')[0]
numbers = choices.split(' ')[1]
if lengths.isdigit() and numbers.isdigit():
for n in range(int(numbers)):
if t not in ['1','2','6']:
password = Createpassword(t1,int(lengths)-2)
password1 = 'YX' + password
print(password1)
else:
password2 = Createpassword(t1,int(lengths))
print(password2)
print('
')
input('按任意键退出!')
break
else:
print('请按要求输入(输入的是两个数字)!')
except:
print('请按要求输入!')
else:
print('请输入1-8的数字!')
t = input('***请选择类型:')
exe效果图如下: