re随机模块应用-生成验证码(无图片)

方法一,通过choice方式生成验证码

此方法生成每次调用crate_code()会生成三个随机数,然后再三个随机数中选择一个,资源调用相对多些

import random

def v_code(code_length):
    res = []
    if isinstance(code_length,int):
        for i in range(code_length):
            ret = create_code()
            res.append(ret)
        return res
    else:
        print("请以数字形式输入多少位")


def create_code():   #生成随机验证码,通过随机choice的方式
    num = chr(random.randint(48, 57)) #随机数字
    alfs = chr(random.randint(65, 90)) #随机大写字母
    alfb = chr(random.randint(97, 122)) #随机大写字母
    s = str(random.choice([num,alfs,alfb]))
    return s
    #方法二,通过指定一个choice的方式指定
    # choice = random.randint(1,3)
    # if choice == 1:
    #     return chr(random.randint(48, 57)) #随机数字
    # elif choice ==2:
    #     return chr(random.randint(65, 90)) #随机大写字母
    # elif choice ==3:
    #     return chr(random.randint(97, 122)) #随机小写字母

if __name__ == "__main__":
    code = v_code(4)
    for i in range(4):
        code[i] = str(code[i])
    code_str =  ''.join(code)
    print("数组类型的展示为:",code)
    print("转换成str类型后:",code_str)

方法二,通过random生成choice

此根据choice方式一次生成一次随机数

import random

def v_code(code_length):
    res = []
    if isinstance(code_length,int):
        for i in range(code_length):
            ret = create_code()
            res.append(ret)
        return res
    else:
        print("请以数字形式输入多少位")


def create_code():   #生成随机验证码,通过随机choice的方式
    # num = chr(random.randint(48, 57)) #随机数字
    # alfs = chr(random.randint(65, 90)) #随机大写字母
    # alfb = chr(random.randint(97, 122)) #随机大写字母
    # s = str(random.choice([num,alfs,alfb]))
    # return s
    #方法二,通过指定一个choice的方式指定
    choice = random.randint(1,3)
    if choice == 1:
        return chr(random.randint(48, 57)) #随机数字
    elif choice ==2:
        return chr(random.randint(65, 90)) #随机大写字母
    elif choice ==3:
        return chr(random.randint(97, 122)) #随机小写字母

if __name__ == "__main__":
    code = v_code(4)
    for i in range(4):
        code[i] = str(code[i])
    code_str =  ''.join(code)
    print("数组类型的展示为:",code)
    print("转换成str类型后:",code_str)

转载于:https://www.cnblogs.com/chrrydot/p/9800889.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值