1 ramdom.sample 实现
from random import samplestr_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_nnum = int(input('输入验证码长度:'))check_code = ''.join(sample(str_a, num))print(check_code)
系统库string
import string # 导入string这个模块from random import sample,choiceprint(string.digits) # 输出包含数字0~9的字符串print(string.ascii_letters) # 包含所有字母(大写或小写)的字符串print(string.ascii_lowercase) # 包含所有小写字母的字符串print(string.ascii_uppercase) # 包含所有大写字母的字符串# samplestr = string.digits + string.ascii_letterscheck_code = ''.join(sample(str, 8))print(check_code)# choicech = ''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 ch15 16 17 def check_code2(num):18 ch = ''.join(sample(ALL_STR,num))19 return ch20 21 num = int(input('验证码长度:'))22 print(check_code1(num))23 print(check_code2(num))