方法一,通过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)
posted on 2018-10-16 21:45  cherrydot  阅读(118)  评论(0编辑  收藏  举报