将字符串加在一起会添加括号和引号

Adding strings together adds brackets and quotation marks

我是编程新手,正在尝试通过做小项目来学习它。目前我正在研究一个随机字符串生成器,我已经完成了 99%,但我无法按照我想要的方式输出。

首先,这是代码:

import random

def pwgenerator():
    print("This is a randomm password generator.")
    print("Enter the lenght of your password and press enter to generate a password.")

    lenght = int(input())
    template = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!" # this is the sample used for choosing random characters
    generator = ""
    for x in range(lenght): # join fcuntion goes trough str chronologically and I want it fully randomized, so I made this loop
        add_on = str(random.sample(template, 1))
        generator = generator + add_on
        #print(add_on) added this and next one to test if  these are already like list or still strings.
        #print(generator)
    print(generator) # I wanted this to work,  but...
    for x in range(lenght): #...created this,  because I thought that  I created list with "generator" and tried to print out a normal string with this
        print(generator[x], end="")

pwgenerator()

原代码应该是这样的:

 import random
    
def pwgenerator():
    print("This is a randomm password generator.")
    print("Enter the lenght of your password and press enter to generate a password.")

    lenght = int(input())
    template = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!"
    generator = ""
    for x in range(lenght):
        generator = generator + str(random.sample(template, 1))
    print(generator)

pwgenerator()

问题是使用这个原始代码和例如输入 10 我得到这个结果:

['e']['3']['i']['E']['L']['I']['3']['r']['l']['2']

我想要的输出是“e3iELI3rl2”

正如您在第一个代码中看到的那样,我尝试了一些操作,因为在我看来我正在以某种方式创建一个包含列表作为项目的列表,每个列表都有 1 个条目。所以我虽然我会打印出每个项目,但结果是(对于用户 input/lenght of 10):

['e']['3']

所以它只是将该列表中的每个字符打印为字符串(包括方括号和引号),我将其解释为我创建的不是列表。但实际上还是一个字符串

做一些研究 - 假设我仍然创建了一个字符串 - 我从 W3Schools 找到了 this。如果我对它的理解是正确的,尽管我在尝试将字符串加在一起时所做的一切都是正确的。

你能告诉我这是怎么回事吗,特别是为什么我得到的输出看起来像一个列表列表? 如果你能抽出更多时间,我也想听听更好的方法,但我主要想了解发生了什么,而不是得到解决方案。我想自己找到解决方案。 :D

干杯

PS: 以防万一你想知道:我正在尝试边做边学,目前正在遵循 HERE 中建议的迷你项目。但在这种情况下,我在 W3Schools 上读到,“加入”方法会产生按时间顺序排列的结果,因此我添加了使其真正随机的额外复杂性。

好的,所以问题是 random.choice returns 字符串列表而不是如下所示的字符串:

template = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!"
random.sample(template, 1)
Out[5]: ['H']

那里实际发生的事情是添加包含列表转换结果的字符串(例如 ['H'] 被转换为“['H']”,然后在屏幕上打印为 ['H']).

将函数修改为 random.choice 后效果很好:

random.choice(template)
Out[6]: 'j'

在您的函数中将此 random.sample 切换为 random.choice,它将如您所愿。

random.sample() 函数returns 从给定的字符串中选择一个列表。 这就是为什么你会得到一堆堆在一起的列表。