zoukankan      html  css  js  c++  java
  • 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()

    打完手工,上妹子:

  • 相关阅读:
    Css进阶
    Css布局
    遇到的小问题
    MySQL 8.017连接Navicat中出现的问题
    ConcurrentHashMap图文源码解析
    HashMap图文源码解析
    接口和抽象类
    dependencies 和 devDependencies
    2020.7.7第二天
    2020.7.6第一天
  • 原文地址:https://www.cnblogs.com/TeyGao/p/6810380.html
Copyright © 2011-2022 走看看