python怎么生成随机密码

1098
2023/8/30 23:22:30
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

Python中可以使用random模块来生成随机密码。下面是一个生成随机密码的示例代码:

import random
import string
def generate_password(length):
chars = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choice(chars) for _ in range(length))
return password
length = int(input("请输入密码长度:"))
password = generate_password(length)
print("随机密码为:", password)

运行代码后,程序会要求输入密码长度,然后生成相应长度的随机密码。random.choice(chars)函数用于从chars字符串中随机选择一个字符,''.join()函数用于将选择的字符连接起来形成密码。string.ascii_letters表示所有的字母,string.digits表示所有的数字,string.punctuation表示所有的标点符号。你也可以根据需要修改chars字符串来控制密码所包含的字符类型。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: Python中for range的用法是什么