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


在浏览别人博客时学习了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()

 

打完手工,上妹子:


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM