用random随机生成验证码

要用random方式随机生成一个6位验证码,必须包含大小写字母、数字和其它字符,而且要求首位为大写字母,末位为数字,其它位置至少包含一个特殊字符,怎么才能让验证码实现这些要求?


import random


def auth_code(count=6):
    res = []
    #首位为大写字母
    ch1 = chr(random.randint(65, 90))  # 随机大写字母
    #末位为数字
    ch6 = str(random.randint(0, 9))  # 随机数字
    #其它位置至少包含一个特殊字符
    special_chs = ['@', '#', '$', '%', '&']
    ch_s = random.choice(special_chs)
    #生成特殊字符的位置
    position = random.randint(0,count-2)

    #必须包含小写字母
    lower = chr(random.randint(97, 122))  # 随机小写字母
    # 生成小写字母的位置
    lower_position = random.randint(0,count-2)

    for i in range(count-4):  #其他位置的随机生成
        d1 = chr(random.randint(97, 122))  # 随机小写字母
        d2 = chr(random.randint(65, 90))  # 随机大写字母
        d3 = str(random.randint(0, 9))  # 随机数字
        d4 = random.choice(special_chs) # 随机特殊字符
        res2 = random.choice([d1, d2, d3,d4])  # 三者之间随机取走一个
        res.append(res2)

    res.insert(position,ch_s)
    res.insert(lower_position,lower)

    return ch1+''.join(res)+ch6


print(auth_code(6))
print(auth_code(6))
print(auth_code(6))
print(auth_code(6))

运行结果:

img

  • 帮你找了个相似的问题, 你可以看下: https://ask.csdn.net/questions/7737670
  • 你也可以参考下这篇文章:random随机生成5位验证码(数字、大写字母、小写字母)
  • 除此之外, 这篇博客: random 模块中的 2.生成指定位数的验证码, 含大小写英文和数字 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
  • import random
    
    def auth_code(count=6):
        res = ''
        for i in range(count):
            lower = chr(random.randint(97,122))  # 随机小写字母
            upper = chr(random.randint(65,90))   # 随机大写字母
            num = str(random.randint(0,9))       # 随机数字
            res2 = random.choice([lower,upper,num])  # 三者之间随机取走一个
            res += res2  # 字符拼接
        return res
    
    print(auth_code(6))  # Fr58Vg
    print(auth_code(6))  # v0IOY8
    print(auth_code(6))  # I9Z2gf
    print(auth_code(6))  # J9128t
    

from random import choice,sample
import string
# 大写字母: string.ascii_uppercase
# 数字: string.digits
# 大小写字母: string.ascii_letters
# 特殊字符对应的位置: 33-44 58-64
specical_code = ''.join( [ chr(i) for i in range(33,45) ] ) + ''.join( [ chr(i) for i in range(58,65) ] )

password = choice( string.ascii_uppercase ) + ''.join( sample( string.ascii_letters + string.digits + specical_code,4 ) ) + choice(string.digits)
print( password )