Skip to content
Advertisement

How to select the values and the length of a random string? [closed]

I made a list of the characters that I want in the string and also know the length. I just don’t know where to announce the characters that I want to use.`

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"))
        

Advertisement

Answer

You can just create an empty list and loop over however many random characters you want and append them to the list, then you join them into a single string and return.

also, you really want to use int(input("Enter a int between 6 & 12 ")) instead of float(input("Enter a float between 6 & 12")) since range only accepts ints and not floats.

    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

this function can also be simplified down to this using comprehension expression:

    def creat_password(self):
        length = int(input("Enter a int between 6 & 12 "))
        return ''.join(secrets.choice(characters) for i in range(length))
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement