python 验证码生成(非图形)

import random


# 功能:生成指定长度随机数字+字母的验证码
def txt_str1(num):
    # 验证码长度
    i = num
    char_strings = ""
    for i in range(0, i):
        # 临时随机数做判断选择是出数字还是字母
        temp = random.randrange(0, 11)
        if temp >= 5:
            # 产生数字(1-9)
            char_strings += str(random.randrange(0, 10))
        else:
            # 临时随机数做判断选择是出小写字母还是大写字母
            temp = random.randrange(0, 11)
            if temp >= 5:
                # 产生小写字母(a-z)
                char_strings += chr(random.randrange(97, 123))
            else:
                # 产生产生大写字母(A-Z)
                char_strings += chr(random.randrange(65, 91))
    return char_strings


# 列表式随机生成验证码
def txt_str2(num):
    # 验证码长度
    i = num
    # 指定会出现的字符串
    lists = ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
             "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u",
             "v", "x", "y", "z",
             "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U",
             "V", "X", "Y", "Z",)
    char_strings = ""
    for i in range(0, i):
        char_strings += str(lists[random.randrange(0, 60)])
    return char_strings


# 精简方式
def txt_str3(num):
    char_strings = ''
    for i in range(num):
        number = random.randrange(48, 58)  # 数字0-9
        abc = random.randrange(97, 123)  # 字母a-z
        ABC = random.randrange(65, 91)  # 字母A-Z
        select = random.choice([number, abc, ABC])  # 随机选择一个
        char_strings += chr(select)
    return char_strings


if __name__ == "__main__":
    print(txt_str1(6))
    print(txt_str2(6))
    print(txt_str3(6))

# ASCII码:
# 123-126 { | } ~
# 97-122 小写字母a-z
# 91-96 : ; < = > ? @
# 65-90 大写字母A-Z
# 58-64 [ \ ] ^ _ `
# 48-57 数字0-9
# 33-47 ! " # $ % & ' ( ) * + , - . /
# 可见符:!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章