【问题标题】:How to select the values and the length of a random string? [closed]如何选择随机字符串的值和长度? [关闭]
【发布时间】:2021-03-22 06:32:17
【问题描述】:

我在字符串中列出了我想要的字符并且还知道长度。我只是不知道在哪里宣布角色 我想使用的。`

import random
characters = ("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", ":", ";", "<", "=", ">", "?", "@", "[",
              "]", "/", "^", "_", "'")


class Password:
    def creat_password(self):
        length = float(input("Enter a float between 6 & 12"))
        

【问题讨论】:

标签: python python-3.x random passwords


【解决方案1】:

您可以创建一个空列表,然后循环遍历任意数量的随机字符并将它们附加到列表中,然后将它们连接成一个字符串并返回。

另外,您真的想使用 int(input("Enter a int between 6 &amp; 12 ")) 而不是 float(input("Enter a float between 6 &amp; 12")),因为 range 只接受整数而不接受浮点数。

    def creat_password(self):
        length = int(input("Enter a int between 6 & 12 "))

        pw_chars = []

        for i in range(length):
            pw_chars.append(secrets.choice(characters))

        password = ''.join(pw_chars)

        return password

这个函数也可以使用理解表达式简化为:

    def creat_password(self):
        length = int(input("Enter a int between 6 & 12 "))
        return ''.join(secrets.choice(characters) for i in range(length))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-25
    • 2021-02-09
    • 1970-01-01
    相关资源
    最近更新 更多