python生成随机的几位验证码

时间:2023-04-30 15:21:51 类型:python
字号:    

生成验证码是咱们日常登陆验证经常需要的应用,那么在python中该如何生成呢?

import random
def createRand(num:int=4, type:int=0)->str:
    '''
    :param num: 要生成 num 个随机数
    :param type: 0: 数字, 1:字母, 2: 字母+数字混合, 3: 中文
    :return: 返回 num 个字符组成 字符串
    '''
    tum = (
        [0, 2, 3, 4, 5, 6, 7, 8, 9],
        ["A", "B", "C", "D", "E", "F", "G", "H", "I", "G", "K", "L", "M", "N"],
        [0, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F", "G", "H", "I", "G", "K", "L", "M", "N"],
        ["你", "我", "他", "大", "家", "好", "中", "国", "人", "是", "伟", "大", "的", "淄", "博"]
    )
    strs = ""
    i = 1
    while i <= num:
        letter = str(random.choice(tum[type]))
        strs += letter
        i = i + 1
    return strs

print(createRand(4, 0))
print(createRand(4, 1))
print(createRand(4, 2))
print(createRand(4, 3))


<