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

Python–随机生成指定长度的密码 标签:import class 随机 博客 学习 let

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

标签:importclass随机博客学习letandportlogs

在浏览别人博客时学习了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–随机生成指定长度的密码

标签:importclass随机博客学习letandportlogs

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

作者: 雨林木风

为您推荐

返回顶部