• 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()

    打完手工,上妹子:

  • 相关阅读:
    pair<,>
    PTA 5-8 File Transfer (25)
    PTA 5-6 Root of AVL Tree (25)
    PTA 5-5 Tree Traversals Again (25)
    HDU4288 Coder(线段树)
    CodeForces 371D Vessels(树状数组)
    POJ2762 Going from u to v or from v to u(单连通 缩点)
    LightOJ 1030 Discovering Gold(期望 概率)
    HDU5115 Dire Wolf(区间DP)
    HDU4008 Parent and son(树形DP LCA)
  • 原文地址:https://www.cnblogs.com/TeyGao/p/6810380.html
Copyright © 2020-2023  润新知