Python随机生成一个6位的验证码代码分享

作者:junjie 时间:2021-03-16 10:41:54 

1. 生成源码


# -*- coding: utf-8 -*-

import random

def generate_verification_code():
    ''' 随机生成6位的验证码 '''
    code_list = []
    for i in range(10): # 0-9数字
        code_list.append(str(i))
    for i in range(65, 91): # A-Z
        code_list.append(chr(i))
    for i in range(97, 123): # a-z
        code_list.append(chr(i))

    myslice = random.sample(code_list, 6)  # 从list中随机获取6个元素,作为一个片断返回
    verification_code = ''.join(myslice) # list to string
    # print code_list
    # print type(myslice)
    return verification_code

def generate_verification_code2():
    ''' 随机生成6位的验证码 '''
    code_list = []
    for i in range(2):
        random_num = random.randint(0, 9) # 随机生成0-9的数字
        # 利用random.randint()函数生成一个随机整数a,使得65<=a<=90
        # 对应从“A”到“Z”的ASCII码
        a = random.randint(65, 90)
        b = random.randint(97, 122)
        random_uppercase_letter = chr(a)
        random_lowercase_letter = chr(b)

        code_list.append(str(random_num))
        code_list.append(random_uppercase_letter)
        code_list.append(random_lowercase_letter)
    verification_code = ''.join(code_list)
    return verification_code

if __name__ == '__main__':
    code = generate_verification_code()
    code2 = generate_verification_code2()
    print code
    print code2

其中的一个生成结果如下:


gF5UzK
2Cb1Aa

标签:Python,随机,验证码
0
投稿

猜你喜欢

  • Python实现井字棋小游戏

    2023-04-27 05:29:07
  • CentOS7 LNMP+phpmyadmin环境搭建 第三篇phpmyadmin安装

    2023-10-17 03:23:18
  • Python+Pygame制作"长沙版"大富翁

    2023-10-05 06:53:08
  • python的pdb调试命令的命令整理及实例

    2022-10-01 01:47:12
  • Opera Mini 5 网站开发速记

    2010-04-20 16:29:00
  • Python @property使用方法解析

    2021-10-27 05:42:46
  • 浅谈flask源码之请求过程

    2023-12-17 10:36:48
  • python使用timeit时间模块

    2023-03-05 16:27:37
  • 通过asp程序来创建access数据库

    2011-04-02 11:17:00
  • 深入了解python列表(LIST)

    2022-09-04 18:25:55
  • 如何配置一个稳定的SQL Server数据库

    2008-12-09 14:07:00
  • python io.BytesIO简介及示例代码

    2021-04-25 04:52:31
  • python 通过文件夹导入包的操作

    2023-03-10 12:48:24
  • Python排序算法之插入排序及其优化方案详解

    2021-04-03 05:39:31
  • python星号(*)和双星号(**) 函数动态参数匹配及解包操作方法

    2023-04-09 19:55:03
  • asp代码WinHttp.WinHttpRequest.5.1使用例子

    2010-03-11 21:28:00
  • Python快速生成随机密码超简单实现

    2022-08-07 19:26:09
  • Python基类函数的重载与调用实例分析

    2021-03-02 21:28:30
  • Python爬虫之urllib库详解

    2022-01-09 23:03:27
  • 解决python matplotlib imshow无法显示的问题

    2023-07-19 23:59:25
  • asp之家 网络编程 m.aspxhome.com