实现功能:Python 代码生成随机密码
以下代码生成一个包含大小写字母、数字和特殊字符的随机密码,长度为 12 个字符:
import random
import string
def generate_random_password(length=12):
characters = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choice(characters) for _ in range(length))
return password
print(generate_random_password())
代码说明
- string.ascii_letters 包含所有大小写字母(A-Z, a-z)。
- string.digits 包含数字 0-9。
- string.punctuation 包含常见特殊字符(如 !, @, # 等)。
- random.choice 从字符集中随机选取字符。
- 默认密码长度为 12,可通过修改 length 参数调整。
运行示例输出可能为:



