You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python密码生成器:如何打乱生成的密码字符序列?

解决密码生成器的字符打乱问题

你当前的密码生成逻辑是按字母、数字、符号的固定顺序拼接字符,所以会出现规律化的密码结构。要实现字符完全随机打乱,只需利用random模块的shuffle()方法对合并后的字符列表进行原地重排即可,具体修改如下:

修改后的完整代码

import random 
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']

print("Welcome to the PyPassword Generator!")
nr_letters= int(input("How many letters would you like in your password?\n")) 
nr_symbols = int(input(f"How many symbols would you like?\n"))
nr_numbers = int(input(f"How many numbers would you like?\n"))

letterlist = []
numberlist = []
symbollist = []
for l in range(nr_letters):
  letterlist.append(random.choice(letters))
for n in range(nr_numbers):
  numberlist.append(random.choice(numbers))
for s in range(nr_symbols):
  symbollist.append(random.choice(symbols))

# 合并所有字符为一个列表
combined_chars = letterlist + numberlist + symbollist
# 原地打乱列表元素顺序
random.shuffle(combined_chars)
# 转换为最终密码字符串
password = "".join(combined_chars)

print("Your password is "+password)

关键修改说明

  • 保留合并后的列表形式:不要直接将字母、数字、符号列表拼接后转成字符串,先存储为combined_chars列表
  • 使用random.shuffle():该方法会直接修改原列表,将元素随机重新排列,这是实现打乱的核心步骤
  • 最后转字符串:将打乱后的列表通过join()方法转换为最终的密码字符串

修改后生成的密码会是字母、数字、符号完全随机混合的形式,比如4!dU5a@这类无规律的组合。

内容的提问来源于stack exchange,提问作者Mathew Still

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 15:33:24