在Python中生成随机密码可以通过以下几种方式实现:
1. 使用`random`模块:
import randomimport stringdef generate_password(length):chars = string.ascii_letters + string.digits + string.punctuationpassword = ''.join(random.choice(chars) for _ in range(length))return passwordlength = int(input("请输入密码长度: "))password = generate_password(length)print("随机密码为: ", password)
2. 使用`secrets`模块:
import secretsimport stringdef generate_password(length=12):alphabet = string.ascii_letters + string.digits + string.punctuationpassword = ''.join(secrets.choice(alphabet) for _ in range(length))return passwordpassword = generate_password()print(password)
3. 使用`faker`模块生成随机密码,并排除以`?`和`!`开头的密码:

from faker import Fakerfake = Faker()def generate_password(length=12):while True:password = ''.join(fake.random_alphanumeric(length) for _ in range(length))if not password.startswith(('!', '?')):breakreturn passwordpassword = generate_password()print(password)
4. 使用`random.sample`函数生成不重复的随机密码:
import randomdef 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 + list2while True:password = ''.join(random.sample(all_chars, length))if not password.startswith(('!', '?')):breakreturn passwordprint(random_password())
