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

如何在Python中打乱字符串?密码生成器开发技术求助

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

当前代码生成的密码会固定按「字母→符号→数字」的顺序排列,缺乏随机性。以下两种方法可以帮你打乱密码的字符顺序:

方法一:用random.shuffle()打乱字符列表

先把所有选中的字符存入列表,再通过shuffle()打乱列表顺序,最后转为字符串:

#Password Generator Project
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"))

# 用列表存储字符,方便后续打乱
password_list = []

for _ in range(nr_letters):
  password_list.append(random.choice(letters))

for _ in range(nr_symbols):
  password_list.append(random.choice(symbols))

for _ in range(nr_numbers):
  password_list.append(random.choice(numbers))

# 随机打乱列表内的字符顺序
random.shuffle(password_list)

# 将列表转为最终的密码字符串
password = ''.join(password_list)

print(f"Your password is: {password}.")

random.shuffle()会直接修改原列表的元素顺序,确保所有字符完全随机排列,最后用join()方法将列表拼接成字符串即可。

方法二:生成时随机选择字符类型

直接在生成每个字符时随机选择类型,同时控制每种类型的剩余数量,生成的密码天然就是打乱状态:

#Password Generator Project
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"))

password = ""
total_chars = nr_letters + nr_symbols + nr_numbers

# 循环生成每个字符,随机选择类型并控制剩余数量
for _ in range(total_chars):
    choice = random.randint(1,3)
    if choice == 1 and nr_letters > 0:
        password += random.choice(letters)
        nr_letters -= 1
    elif choice == 2 and nr_symbols > 0:
        password += random.choice(symbols)
        nr_symbols -= 1
    elif choice == 3 and nr_numbers > 0:
        password += random.choice(numbers)
        nr_numbers -= 1

print(f"Your password is: {password}.")

这种方法每次循环随机挑选字符类型,同时减少对应类型的剩余计数,确保最终生成的字符数量完全符合用户输入的要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 09:55:22