代码:
import random
import string
def custom_password(length):
# 定义包含所有可能字符的字符串
all_chars = string.ascii_letters + string.digits + string.punctuation
# 生成密码
password = ''.join(random.choice(all_chars) for _ in range(length))
return password
# 生成一个长度为10的密码
password = custom_password(10)
print(password)
运行结果:
[-A+]PK|$l
t,(D!2&[EV
Emekj''N->
注释:
random.choice()
函数从all_chars
中随机选择一个字符。
for _ in range(length)
:使用 _ 占位符 列表推导式的方法将值赋值给前面
''.join(...)
:join()
方法将生成器对象中的字符连接成一个字符串,使用空字符串''
作为分隔符。