Signup/Sign In

Generating a Random String in Python

Posted in Programming   LAST UPDATED: OCTOBER 13, 2021

    It is suggested to keep changing passwords often (once every three to six months) to safeguard your online accounts against attacks. There are systems that dynamically generate a password for a user every time they try to log in. Such systems use random password generators which generate random passwords every time. This way, the user themselves wouldn't know the password but still would be safe from external attacks.

    On the same lines, we will look at different methods of generating random string given a limit for the length of the randomly generated string.

    1. Using random.choices method

    The random module has many functions, and one of the functions is choices. This can be used as a one-liner instead of writing an entire loop to generate a random string. This function works with Python versions 3.6 and above.

    Let's take an example,

    import string 
    import random 
    
    N = 12
    
    my_pwd = ''.join(random.choices(string.ascii_uppercase + string.digits, k = N)) 
    print("The generated random password : " + str(my_pwd)) 

    Output:

    The generated random password : Z2LO343W8X9N

    Note: Every time the above code is run, a new 12 character string is generated.


    2. Using secrets.choice method

    The secret module also has a choice(not choices) function which can be used to generate random strings, which are cryptographically secure. This is because the secret module's internal algorithm has been designed in a way such that the random numbers generated are less predictable by attackers. This function works with Python version 3.6 and above.

    Let's take an example for this too,

    import string 
    import secrets 
    
    N = 12
    
    my_pwd = ''.join(secrets.choice(string.ascii_uppercase + string.digits) for i in range(N)) 
    print("The generated random password : " + str(my_pwd))

    Output:

    The generated random password : 6PR0JGE9NAVY

    Note: It is usually suggested that a strong password should have lower case characters, upper case characters, numbers, and special symbols.


    Conclusion

    In this post, we understood two different ways of generating random strings in Python. Do let us know how you would approach this problem.

    You may also like:

    About the author:
    I love writing about Python and have more than 5 years of professional experience in Python development. I like sharing about various standard libraries in Python and other Python Modules.
    Tags:PythonPython StringPython Random
    IF YOU LIKE IT, THEN SHARE IT
     

    RELATED POSTS