小记一次考题:生成包含大写字母、小写字母、数字的8位密码

思路一:str=‘abcd.....xyz0123456789ABCD....XYZ’     

思路二:str1='abcd...'  str2='ABCD....XYZ'   str3='0123456789'

思路三:引入string    使用   string.ascii_lowercase 等

思路四:引入ASCII    使用随机以及正则      目前感觉是比较正确的    有待优化

 1 # -*- coding: utf-8 -*-
 2 # @Time    : 2018/10/8 16:24
 3 # @Author  : wangyafeng
 4 # @Email   : 279949848@qq.com
 5 # @Software: PyCharm
 6 
 7 
 8 import random,re
 9 
10 checkcode = ''
11 for i in range(8):
12     current = random.randrange(0,100)
13     # 字母
14     if current%2==0:
15         tmp=chr(random.randint(65,90))
16         checkcode += str(tmp)
17     elif current%3==0:
18         tmp=chr(random.randint(97,122))
19         checkcode += str(tmp)
20     #数字
21     else:
22         tmp=random.randint(0,9)
23         checkcode += str(tmp)
24 
25 # matchObj=re.match('^[A-Za-z0-9]{8}$',checkcode)
26 matchObj=re.match('^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).{8}$',checkcode)
27 if matchObj:
28     print(checkcode)
29 else:
30     print("请重新生成")

 

今天彻底解决这个问题 ,尚待代码继续优化,但是终归是解决了  这个思路还是比较简单的

 1 import random
 2 listc=[]
 3 listd=[]
 4 liste=[]
 5 for i in range(65,91):
 6     listc.append(chr(i))
 7 for j in range(97,123):
 8     listd.append(chr(j))
 9 for k in range(48,58):
10     liste.append(chr(k))
11 
12 while True:
13     a=random.randint(1,6)
14     if 6-a>1:
15         b=random.randint(1,6-a)
16     else:
17         b=random.randint(1,1)
18     if  6-a-b>1:
19         c=random.randint(1,6-a-b)
20     else:
21         c=random.randint(1,1)
22 
23     chart=random.sample(listc,a)+random.sample(listd,b)+random.sample(liste,c)
24     chart=''.join(chart)
25     if len(chart) ==6:
26         print(chart)
27         break

 

# #数字 48--57  大写字母 65--90  小写字母 97--122
# #优化版本  生成随机8位密码
list_num = []
for x in range(48, 58):
    list_num.append(chr(x))
for y in range(65, 90):
    list_num.append(chr(y))
for z in range(97,122):
    list_num.append(chr(z))

char_list = []
for i in range(8):
    char = list_num[random.randint(0, len(list_num)) - 1]
    char_list.append(char)
secter = ''.join(char_list)
print(secter)

 

posted @ 2018-10-08 16:49  王亚锋  阅读(944)  评论(0编辑  收藏  举报