在Python中生成随机密码可以通过以下几种方式实现:
1. 使用`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)
2. 使用`secrets`模块:
import secrets
import string
def generate_password(length=12):
alphabet = string.ascii_letters + string.digits + string.punctuation
password = ''.join(secrets.choice(alphabet) for _ in range(length))
return password
password = generate_password()
print(password)
3. 使用`faker`模块生成随机密码,并排除以`?`和`!`开头的密码:
from faker import Faker
fake = Faker()
def generate_password(length=12):
while True:
password = ''.join(fake.random_alphanumeric(length) for _ in range(length))
if not password.startswith(('!', '?')):
break
return password
password = generate_password()
print(password)
4. 使用`random.sample`函数生成不重复的随机密码:
import random
def random_password(length=8):
list1 = [chr(i) for i in range(65, 90)] + [chr(i) for i in range(97, 122)]
list2 = [str(i) for i in range(10)]
all_chars = list1 + list2
while True:
password = ''.join(random.sample(all_chars, length))
if not password.startswith(('!', '?')):
break
return password
print(random_password())