如何在Python中随机指定变量

我正在创建一个密码生成器,它获取所需密码的长度、字母数量以及数字数量。密码需要包含大写字母以及数字和特殊字符。我无法弄清楚如何指定密码中的字母和数字的数量。这是我到目前为止所拥有的:


import random


charslet ="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

charsnum = "1234567890"

charssym = "!@#$%^&*"


def password():

    pwd = ""


    passlen = int(input("How long do you want the password to be?: "))

    passlet = int(input("How many letters do you want in your password?: "))

    passnum = int(input("How many numbers do you want in your password?: "))

    passsym = int(passlen - (passlet + passnum))

    chars = ""


    for let in range(passlet):

        chars += random.choice(charslet)

    for num in range(passnum):

        chars += random.choice(charsnum)

    for sym in range(passsym):

        chars += random.choice(charssym)




    for p in range(passlen):

        pwd += random.choice(chars)


    print(pwd)


password()


紫衣仙女
浏览 96回答 2
2回答

冉冉说

我认为最后一部分让你感到困惑。您正在使用chars正确数量的特定字符构建变量,但最后您再次在它们之间进行选择。你可以改变:for p in range(passlen):    password += random.choice(chars)和# option 1 - works better if working with listslist_chars = list(chars)random.shuffle(chars)password = "".join(list_chars)# option 2 - simpler solution for stringspassword = "".join(random.sample(char, len(char)))您还可以使用 shuffle 来选择之前的字符,而不使用 for 循环,例如:# for this to work your `charslet` must be a listrandom.shuffle(charslet)chars += "".join(charslet[:passlet])

米脂

这是更正后的代码:    import random    charslet ="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"    charsnum = "1234567890"    charssym = "!@#$%^&*"    def password():        pwd = ""        passlen = int(input("How long do you want the password to be?: "))        passlet = int(input("How many letters do you want in your password?: "))        passnum = int(input("How many numbers do you want in your password?: "))        passsym = int(passlen - (passlet + passnum))        chars = ""        for let in range(passlet):            chars += random.choice(charslet)        for num in range(passnum):            chars += random.choice(charsnum)        for sym in range(passsym):            chars += random.choice(charssym)        list_chars = list(chars)        random.shuffle(list_chars)        pwd = "".join(list_chars)        print(pwd)    password()我替换:    for p in range(passlen):        password += random.choice(chars)和    list_chars = list(chars)    random.shuffle(list_chars)    pwd = "".join(list_chars)将更改后的chars变量放入列表中可以让我对其进行洗牌、随机化并允许我将其分配给pwd
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python