使用所学的知识,从字符串中随机取出4个字符,且验证码必须包含大写字母,小写字母和数字,生成验证码

给定一个字符串,如:
mystr = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
使用所学的知识,从字符串中随机取出4个字符,且验证码必须包含大写字母,小写字母和数字,生成验证码

该回答引用chatgpt:亲测可用


import random

# 给定字符串
mystr = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

# 生成包含大写字母、小写字母和数字的验证码
code = ''
while len(code) < 4:
    char = random.choice(mystr)
    if char.islower() and 'a' not in code:
        code += 'a'
    elif char.isupper() and 'A' not in code:
        code += 'A'
    elif char.isdigit() and '0' not in code:
        code += '0'
    elif char not in code:
        code += char

# 打印验证码
print("生成的验证码为:", code)

img

可以使用Python的random模块来生成随机验证码,以下代码会不断生成随机验证码,直到满足包含大写字母、小写字母和数字的条件。

import random

mystr = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

while True:
    # 从字符串中随机取4个字符
    code = ''.join(random.sample(mystr, 4))
    # 判断验证码是否包含大写字母、小写字母和数字
    if any(c.isupper() for c in code) and any(c.islower() for c in code) and any(c.isdigit() for c in code):
        # 如果满足条件,输出验证码并退出循环
        print("验证码:", code)
        break