生成随机验证码

1   ramdom.sample 实现

from random import sample

str_u = [chr(i) for i in range(97,123)]   # 大写字母
str_l = [chr(i) for i in range(65,91)]    # 小写字母
str_n = [chr(i) for i in range(48,58)]    # 数字

str_a = str_u + str_l + str_n

num = int(input('输入验证码长度:'))

check_code = ''.join(sample(str_a, num))
print(check_code)

 

系统库string

import string   # 导入string这个模块
from random import sample,choice
print(string.digits)  # 输出包含数字0~9的字符串
print(string.ascii_letters)  # 包含所有字母(大写或小写)的字符串
print(string.ascii_lowercase)  # 包含所有小写字母的字符串
print(string.ascii_uppercase)  # 包含所有大写字母的字符串

# sample
str = string.digits + string.ascii_letters
check_code = ''.join(sample(str, 8))
print(check_code)

# choice
ch = ''
for i in range(8):
    ch += choice(str)
print(ch)

 

最终代码如下

 1 from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits
 2 from random import sample, choice
 3 
 4 UPPER = ascii_uppercase
 5 LOWER = ascii_lowercase
 6 LETTER = ascii_letters
 7 DIGIT = digits
 8 ALL_STR = DIGIT + LETTER
 9 
10 def check_code1(num):
11     ch = ''
12     for i in range(num):
13         ch += choice(ALL_STR)
14     return ch
15 
16 
17 def check_code2(num):
18     ch = ''.join(sample(ALL_STR,num))
19     return ch
20 
21 num = int(input('验证码长度:'))
22 print(check_code1(num))
23 print(check_code2(num))

 

posted @ 2019-03-13 19:13  Ray_chen  阅读(384)  评论(0编辑  收藏  举报