生成随机验证码

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))

 

转载于:https://www.cnblogs.com/ray-mmss/p/10525475.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值