码迷,mamicode.com
首页 > 编程语言 > 详细

Python--随机生成指定长度的密码

时间:2017-05-05 00:53:09      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:import   class   随机   博客   学习   let   and   port   logs   

在浏览别人博客时学习了random模块,手痒自我练习下,写个随机生成指定长度的密码字符串的函数,拿出来供各位参考:

废话不多说,上代码:

# coding: utf-8
import random
import string

SPECIAL_CHARS = ~%#%^&*
PASSWORD_CHARS = string.ascii_letters + string.digits + SPECIAL_CHARS


def generate_random_password(password_length=10):
    """
    生成指定长度的密码字符串,当密码长度超过3时,密码中至少包含:
    1个大写字母+1个小写字母+1个特殊字符
    :param password_length:密码字符串的长度
    :return:密码字符串
    """
    char_list = [
        random.choice(string.ascii_lowercase),
        random.choice(string.ascii_uppercase),
        random.choice(SPECIAL_CHARS),
    ]
    if password_length > 3:
        # random.choice 方法返回一个列表,元组或字符串的随机项
        # (x for x in range(N))返回一个Generator对象
        # [x for x in range(N)] 返回List对象
        char_list.extend([random.choice(PASSWORD_CHARS) for _ in range(password_length - 3)])
    # 使用random.shuffle来将list中元素打乱
    random.shuffle(char_list)
    return ‘‘.join(char_list[0:password_length])


def test_password_generate():
    random_password = generate_random_password(password_length=6)
    print(random_password)


test_password_generate()

 

打完手工,上妹子:

技术分享

Python--随机生成指定长度的密码

标签:import   class   随机   博客   学习   let   and   port   logs   

原文地址:http://www.cnblogs.com/TeyGao/p/6810380.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!