如何使1个或多个列表中的随机字母、数字或符号周围没有引号

2024-10-01 13:27:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图在Python3中创建一个随机密码生成器。我设法完成了这个项目,但在完成过程中遇到了一个问题: 我的程序不是简单地输入密码,而是用引号一个接一个地显示字母,这给使用它的人带来了很大的不便。这对我来说并不是什么问题,但因为我是一个初学者,我想好好学习

import random

print("Welcome to the password generator! (Your password should at least total 6 characters) ")
non_capitals = "abcdefghijklmnopqrstuvwxyz"
capitals = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
numbers = "1234567890"
symbols = "!@#¤%&/()?"
notcapcount = int(input("How many lower-case letters?"))
capcount = int(input("How many upper-case letters ?"))
numcount = int(input("How many numbers?"))
symcount = int(input("How many symbols?"))
passlen = notcapcount + capcount + numcount + symcount

password = (random.choices(non_capitals, k = notcapcount)) + (random.choices(capitals, k = capcount)) + (random.choices(numbers, k = numcount)) + (random.choices(symbols, k = symcount))

if passlen < 6:
    print("password is too short")
elif passlen >= 6:
    print(password)`

如果运行此命令,您将在以下行中获得一些内容(不包括要求您输入的位置):

['r', 'r', 'i', 'k', 'W', 'W', 'B', '7', '6', '(']

我认为有一种方法可以解决这个问题,因为这是一个网站上推荐的初学者项目,但我似乎无法理解


Tags: inputrandompasswordmanyhowintchoicesprint
2条回答

这是您更正的代码;有关详细信息,请参见注释。另外,我强烈建议不要将random模块用于任何加密任务。请参阅Can I generate authentic random number with python?了解如何正确操作

import random

print("Welcome to the password generator! (Your password should at least total 6 characters) ")
non_capitals = "abcdefghijklmnopqrstuvwxyz"
capitals = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
numbers = "1234567890"
symbols = "!@#¤%&/()?"
notcapcount = int(input("How many lower-case letters?"))
capcount = int(input("How many upper-case letters ?"))
numcount = int(input("How many numbers?"))
symcount = int(input("How many symbols?"))
passlen = notcapcount + capcount + numcount + symcount

#get all the right characters
password = (random.choices(non_capitals, k = notcapcount)) + (random.choices(capitals, k = capcount)) + (random.choices(numbers, k = numcount)) + (random.choices(symbols, k = symcount)) 

random.shuffle(password) #randomize list order, do this first, because string is immutable
"".join(password) #make string

if passlen < 6:
    print("password is too short")
elif passlen >= 6:
    print(password)

如果要查找字符串,可以执行以下操作:

password = ['r', 'r', 'i', 'k', 'W', 'W', 'B', '7', '6', '(']
password = "".join(password)
print(password)

这将产生

rrikWWB76(

相关问题 更多 >