PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
    • Python Exercises
    • C Programming Exercises
    • C++ Exercises
  • Quizzes
  • Code Editor
    • Online Python Code Editor
    • Online C Compiler
    • Online C++ Compiler
Home » Python » Random » Generate Random Strings and Passwords in Python

Generate Random Strings and Passwords in Python

Updated on: February 16, 2022 | 21 Comments

In this lesson, you will learn how to create a random string and passwords in Python.

Table of contents

  • String Constants
  • How to Create a Random String in Python
    • Example to generate a random string of any length
  • Random String of Lower Case and Upper Case Letters
    • Random string of specific letters
  • Random String without Repeating Characters
  • Create Random Password with Special characters, letters, and digits
    • Random password with a fixed count of letters, digits, and symbols
    • Generate a secure random string and password
  • Generate a random alphanumeric string of letters and digits
    • Random alphanumeric string with a fixed count of letters and digits
  • Generate a random string token
    • Generate universally unique secure random string Id
  • Use the StringGenerator module to generate a random string
  • Next Steps
    • Practice Problem

String Constants

Below is the list of string constants you can use to get a different set of characters as a source for creating a random string.

ConstantDescription
ascii_lowercaseContain all lowercase letters
ascii_uppercaseContain all uppercase letters
ascii_lettersContain both lowercase and uppercase letters
digitsContain digits ‘0123456789’.
punctuationAll special symbols !”#$%&'()*+,-./:;<=>?@[\]^_`{|}~.
whitespaceIncludes the characters space, tab, linefeed, return, formfeed, and vertical tab [^ \t\n\x0b\r\f]
printablecharacters that are considered printable. This is a combination of constants digits, letters, punctuation, and whitespace.
String constants

How to Create a Random String in Python

We can generate the random string using the random module and string module. Use the below steps to create a random string of any length in Python.

  1. Import string and random module

    The string module contains various string constant which contains the ASCII characters of all cases. It has separate constants for lowercase, uppercase letters, digits, and special symbols, which we use as a source to generate a random string.
    Pass string constants as a source of randomness to the random module to create a random string

  2. Use the string constant ascii_lowercase

    The string.ascii_lowercase returns a list of all the lowercase letters from ‘a’ to ‘z’. This data will be used as a source to generate random characters.

  3. Decide the length of a string

    Decide how many characters you want in the resultant string.

  4. Use a for loop and random choice() function to choose characters from a source

    Run a for loop till the decided string length and use the random choice() function in each iteration to pick a single character from the string constant and add it to the string variable using a join() function. print the final string after loop competition

  5. Generate a random Password

    Use the string.ascii_letters, string.digits, and string.punctuation constants together to create a random password and repeat the first four steps.

Example to generate a random string of any length

import random
import string

def get_random_string(length):
    # choose from all lowercase letter
    letters = string.ascii_lowercase
    result_str = ''.join(random.choice(letters) for i in range(length))
    print("Random string of length", length, "is:", result_str)

get_random_string(8)
get_random_string(6)
get_random_string(4)Code language: Python (python)

Output:

Random string of length 8 is: ijarubtd
Random string of length 6 is: ycfxbs
Random string of length 4 is: dpla
  • The random choice() function is used to choose a single item from any sequence and it can repeat characters.
  • The above random strings contain all lower case letters. If you want only the uppercase letters, then use the string.ascii_uppercase constant instead in the place of a string.ascii_lowercase.

Random String of Lower Case and Upper Case Letters

In Python, to generate a random string with the combination of lowercase and uppercase letters, we need to use the string.ascii_letters constant as the source. This constant contains all the lowercase and uppercase letters.

Example

import random
import string

def get_random_string(length):
    # With combination of lower and upper case
    result_str = ''.join(random.choice(string.ascii_letters) for i in range(length))
    # print random string
    print(result_str)

# string of length 8
get_random_string(8)
get_random_string(8)Code language: Python (python)

Output:

WxQqJQlD
NoCpqruK

Random string of specific letters

If you wanted to generate a random string from a fixed set of characters, please use the following example.

import random

# Random string of length 5
result_str = ''.join((random.choice('abcdxyzpqr') for i in range(5)))
print(result_str)
# Output ryxayCode language: Python (python)

Random String without Repeating Characters

Note: The choice() method can repeat characters. If you don’t want repeated characters in a resultant string, then use the random.sample() method.

import random
import string

for i in range(3):
    # get random string of length 6 without repeating letters
    result_str = ''.join(random.sample(string.ascii_lowercase, 8))
    print(result_str)Code language: Python (python)

Output:

wxvdkbfl
ztondpef
voeduias

Warning: As you can see in the output, all characters are unique, but it is less secure because it will reduce the probability of combinations of letters because we are not allowing repetitive letters and digits.

Create Random Password with Special characters, letters, and digits

A password that contains a combination of characters, digits, and special symbols is considered a strong password.

Assume, you want to generate a random password like: –

  • ab23cd#$
  • jk%m&l98
  • 87t@h*ki

We can generate a random string password in Python with letters, special characters, and digits using the following two ways.

  • Combine the following three constants and use them as a data source for the random.choice() function to select random characters from it.
    • string.ascii_letters: To include letters from a-z and A-Z
    • string.digits: To include digits from 1 to 10
    • string.punctuation: to get special symbols
  • Use the string.printable constant and choice() function. The string.printable contains a combination of digits, ascii_letters (lowercase and uppercase letters), punctuation, and whitespace.

Example

import random
import string

# get random password pf length 8 with letters, digits, and symbols
characters = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choice(characters) for i in range(8))
print("Random password is:", password)Code language: Python (python)

Output:

Random password is: 6(I3goZ}

Using the string.printable

import random
import string

password = ''.join(random.choice(string.printable) for i in range(8))
print("Random password is:", password)Code language: Python (python)

Output

Random password is: hY*34jj.

Random password with a fixed count of letters, digits, and symbols

It is a widespread use case that passwords must contain some count of digits and special symbols.

Let’s see how to generate a random password that contains at least one lowercase letter, one uppercase letter, one digit, and one special symbol.

Steps: –

  • First, select the number of random lowercase and uppercase letters specified
  • Next, choose the number of random digits
  • Next, choose the number of special symbols
  • Combine both letters, digits, and special symbols into a list
  • At last shuffle the list
  • Convert list back to a string
import random
import string

def get_random_password():
    random_source = string.ascii_letters + string.digits + string.punctuation
    # select 1 lowercase
    password = random.choice(string.ascii_lowercase)
    # select 1 uppercase
    password += random.choice(string.ascii_uppercase)
    # select 1 digit
    password += random.choice(string.digits)
    # select 1 special symbol
    password += random.choice(string.punctuation)

    # generate other characters
    for i in range(6):
        password += random.choice(random_source)

    password_list = list(password)
    # shuffle all characters
    random.SystemRandom().shuffle(password_list)
    password = ''.join(password_list)
    return password

print("First Random Password is ", get_random_password())
# output  qX49}]Ru!(
print("Second Random Password is ", get_random_password())
# Output  3nI0.V#[TCode language: Python (python)

Generate a secure random string and password

Above all, examples are not cryptographically secure. The cryptographically secure random generator generates random data using synchronization methods to ensure that no two processes can obtain the same data simultaneously.

If you are producing random passwords or strings for a security-sensitive application, then you must use this approach.

If you are using Python version less than 3.6, then use the random.SystemRandom().choice() function instead of random.choice().

If you are using a Python version higher than 3.6 you can use the secrets module to generate a secure random password.

Use secrets.choice() function instead of random.choice()

import secrets
import string

# secure random string
secure_str = ''.join((secrets.choice(string.ascii_letters) for i in range(8)))
print(secure_str)
# Output QQkABLyK

# secure password
password = ''.join((secrets.choice(string.ascii_letters + string.digits + string.punctuation) for i in range(8)))
print(password)
# output 4x]>@;4)Code language: Python (python)

Generate a random alphanumeric string of letters and digits

We often want to create a random string containing both letters and digits such as ab23cd, jkml98, 87thki. In such cases, we use the string.ascii_letters and string.digits constants to get the combinations of letters and numbers in our random string.

Now, let’s see the to create a random string with the combination of a letter from A-Z, a-z, and digits 0-9.

import random
import string

# get random string of letters and digits
source = string.ascii_letters + string.digits
result_str = ''.join((random.choice(source) for i in range(8)))
print(result_str)
# Output vZkOkL97Code language: Python (python)

Random alphanumeric string with a fixed count of letters and digits

For example, I want to create a random alpha-numeric string that contains 5 letters and 3 numbers.

Example

import random
import string

def get_string(letters_count, digits_count):
    letters = ''.join((random.choice(string.ascii_letters) for i in range(letters_count)))
    digits = ''.join((random.choice(string.digits) for i in range(digits_count)))

    # Convert resultant string to list and shuffle it to mix letters and digits
    sample_list = list(letters + digits)
    random.shuffle(sample_list)
    # convert list to string
    final_string = ''.join(sample_list)
    print('Random string with', letters_count, 'letters', 'and', digits_count, 'digits', 'is:', final_string)

get_string(5, 3)
# Output get_string(5, 3)

get_string(6, 2)
# Output Random string with 6 letters and 2 digits is: 7DeOCm5t
Code language: Python (python)

Output:

First random alphanumeric string is: v809mCxH
Second random alphanumeric string is: mF6m1TRk

Generate a random string token

The above examples depend on String constants and random module functions. There are also other ways to generate a random string in Python. Let see those now.

We can use secrets.token_hex() to get a secure random text in hexadecimal format.

import secrets
print("Secure hexadecimal string token", secrets.token_hex(32))Code language: Python (python)

Output:

Secure hexadecimal string token 25cd4dd7bedd7dfb1261e2dc1489bc2f046c70f986841d3cb3d59a9626e0d802

Generate universally unique secure random string Id

The random string generated using a UUID module is suitable for the Cryptographically secure application. The UUID module has various functions to do this. Here in this example, we are using a uuid4() function to generate a random string Id.

import uuid
stringId  = uuid.uuid4()
print("Secure unique string id", stringId)
# Output 0682042d-318e-45bf-8a16-6cc763dc8806Code language: Python (python)

Use the StringGenerator module to generate a random string

The StringGenerator module is not a part of a standard library. However, if you want you can install it using pip and start using it.

Steps: –

  • pip install StringGenerator.
  • Use a render() function of StringGenerator to generate randomized strings of characters using a template

Let see the example now.

import strgen

random_str = strgen.StringGenerator("[\w\d]{10}").render()
print(random_str)
# Output 4VX1yInC9S

random_str2 = strgen.StringGenerator("[\d]{3}&[\w]{3}&[\p]{2}").render()
print(random_str2)
# output "C01N=10Code language: Python (python)

Next Steps

I want to hear from you. What do you think of this article? Or maybe I missed one of the ways to generate random string in Python. Either way, let me know by leaving a comment below.

Also, try to solve the random module exercise and quiz to have a better understanding of working with random data in Python.

Practice Problem

Create a random alphanumeric string of length ten that must contain at least four digits. For example, the output can be anything like 1o32WzUS87, 1P56X9Vh87

Show Solution
import random
import string

digits = string.digits
letter_digit_list = list(string.digits + string.ascii_letters)
# shuffle random source of letters and digits
random.shuffle(letter_digit_list)

# first generate 4 random digits
sample_str = ''.join((random.choice(digits) for i in range(4)))

# Now create random string of length 6 which is a combination of letters and digits
# Next, concatenate it with sample_str
sample_str += ''.join((random.choice(letter_digit_list) for i in range(6)))
aList = list(sample_str)
random.shuffle(aList)

final_str = ''.join(aList)
print("Random String:", final_str)
# Output 81OYQ6D430Code language: Python (python)

Filed Under: Python, Python Random

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Random

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Comments

  1. Thembisa says

    October 20, 2024 at 9:46 pm

    Vishal you’re such a very best teacher. All your python tutorials are always best and understandable. I’m so proud of you. Thank you for sharing this information and education to us. You’re such the most valuable person in our lives. We highly appreciate you a lot for your great work. I’ve learnt so much in your tutorials and I mastered a lot of information and a lot of good skills of programming. I’m so proud of you.

    Reply
  2. Michael says

    March 10, 2023 at 11:32 pm

    In the random module is the warning

    > Warning
    >
    > The pseudo-random generators of this module should not be used for security purposes. For security or cryptographic uses, see the secrets module.

    please don’t use these for passwords

    Reply
    • Vishal says

      April 19, 2023 at 4:11 pm

      If you are producing random passwords or strings for a security-sensitive application, then you can use the secrets module.

      Reply
  3. michelle says

    March 7, 2023 at 4:30 am

    How can I create a password generator that generates a random password based on length and parameters input from user? It also needs to validate the user’s input to ensure it’s an integer for length. It also needs to validate the user’s parameters if they choose yes or no on using upper, lower, digits, and punctuation.

    Reply
  4. Jim says

    October 6, 2022 at 7:58 am

    Nice job! How do I generate more than one password at a time? Say I want to generate 100 random passwords?
    Thanks!

    Reply
    • Script Kitty says

      November 3, 2022 at 2:01 am

      just put print(100)

      Reply
  5. Albert says

    May 12, 2022 at 5:51 am

    How do I create a password generator with certain amounts of each letter like 5 uppercase 3 lower case 2 numbers and so on.

    Reply
    • Ricardo Milos says

      June 3, 2022 at 9:38 pm

      I think there’s an example of a For loop for choosing random.choice(string.ascii_lowercase) 2 times then you add random.choice(string.ascii_uppercase) 3 times

      Reply
  6. alcebytes says

    January 3, 2022 at 10:29 am

    Oie Vishal, Parabéns pelo seu trabalho em desenvolver essa plataforma de estudos, em programação e linguagem de computacional, já rodei acredito que umas 50 vezes por todo o site e acredite sempre consigo aprender coisas novas. a solução pro exercício na prática, ficou assim.

    
    importar
    string de importação aleatória
    
    def password ():
    String = random.sample (string.ascii_letters, 6) + random.sample (string.digits, 4)
    random.SystemRandom (). shuffle (String)
    print ('string alfanumérica aleatória:', ”.join (Corda))
    
    senha ()
    senha ()
    
    # saída:
    string alfanumérica aleatória: yCvPF9l865
    string alfanumérica aleatória: 5EU62PFW8D
    Reply
  7. alcebytes says

    January 3, 2022 at 6:58 am

    Oie Vishal, Parabéns pelo seu trabalho em desenvolver essa plataforma de estudos, em programação e linguagem de computacional, já rodei acredito que umas 50 vezes por todo o site e acredite sempre consigo aprender coisas novas. a solução pro exercício na pratica, ficou assim.

    import random
    import string
    
    def password():
        String = random.sample(string.ascii_letters, 6) + random.sample(string.digits, 4)
        random.SystemRandom().shuffle(String)
        print('string alfanumérica aleatória:', ''.join(String))
    
    password()
    password()

    #saída:
    string alfanumérica aleatória: yCvPF9l865
    string alfanumérica aleatória: 5EU62PFW8D

    Reply
  8. Neel Shah says

    November 24, 2021 at 9:53 am

    Hi Vishal,

    Great article! In my journey to become a sharper automation engineer, this explanation greatly helped me. Although, I came here after reading Secrets module. Seemed easy to follow through. Thank you!!

    Reference: https://docs.python.org/3/library/secrets.html#recipes-and-best-practices

    Here is my trial!

    import string
    import secrets
    characters = string.ascii_letters + string.digits + string.punctuation
    
    
    def generate_password(length):
        return ''.join(secrets.choice(characters) for i in range(length))
    
    
    """def generate_password(length):
        password = ''.join(secrets.choice(characters) for i in range(length))
        if (any(c.islower() for c in password)
                and any(c.isupper() for c in password)
                and sum(c.isdigit() for c in password) >= 3):
        return password"""
    
    
    print(generate_password(8))
    print(generate_password(10))
    print(generate_password(12))
    print(generate_password(16))
    Reply
  9. OutsiderLost says

    September 11, 2021 at 1:59 am

    I basically understood, even though I’m a beginner in python.

    I figured this out myself, I emptied more things, it may not make much sense, but suddenly it popped out of my head when analyzing the scripts:
    (Many strings are separate because I didn’t need a value of 0.) 🙂

    
    import secrets
    import random
    import string
    
    for i in range(10):
      def get_random_string(length):
        # choose from all letter and number
        letters = string.ascii_lowercase
        upperc = string.ascii_uppercase
        numbers = '123456789'
        result_str1 = ''.join(random.choice(letters + upperc + numbers) for i in range(length))
        result_str = ''.join(secrets.choice(letters + upperc + numbers) for i in range(length))
        print('1.->', result_str1)
        print('2.->', result_str)
    
      get_random_string(8)
      
    for i in range(10):
      def get_random_string1(length):
        # choose from all letter and number
        letters = string.ascii_lowercase
        upperc = string.ascii_uppercase
        numbers = '123456789'
        result_str01 = ''.join(random.choice(letters + upperc + numbers) for i in range(length))
        result_str02 = ''.join(secrets.choice(letters + upperc + numbers) for i in range(length))
        print('3.->', result_str01 + result_str02)
    
      get_random_string1(2+2)
      
       # 10 of each variant should be listed by sequence number.
    Reply
  10. checkmycode_ says

    January 21, 2021 at 7:56 am

    import random
    e =[]
    g =[]
    f =0
    a =['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
    x = 9
    b =['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h','i', 'j', 'k', 'm', 'n', 'o', 'p', 'q','r', 's', 't', 'u', 'v', 'w', 'x', 'y','z']
    c =['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',  'I', 'J', 'K', 'M', 'N', 'O', 'p', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y','Z']
    d =['@', '#', '$', '%', '=', ':', '?', '.', '/', '|', '~', '>','*', '(', ')', '<&#','039']
    j =[]
    
    while f!=4:
        z = random.randint(0,int(x))
        e.append(a[z])
        f+=1
    for i in range(f):
         g.append(e[i])
    x = len(b)-1 
    f =0
    e = []   
    while f!=3:
        z = random.randint(0,int(x))
        e.append(b[z])
        f+=1
    for i in range(f):
        g.append(e[i])
    f = 0
    e = []   
    x = len(c)-1
    while f!=3:
        z = random.randint(0,int(x))
        e.append(c[z])
        f+=1
    for i in range(f):
        g.append(e[i])
    f = 0
    e = []   
    x = len(d)-1
    while f!=3:
        z = random.randint(0,int(x))
        e.append(d[z])
        f+=1
    for i in range(f):
        g.append(e[i])
    j=''
    f = 12
    while len(j)!=12:
        z= random.randint(0,f)
        j = j + str(g[z])
        g.remove(g[z])
        f-=1
    j +=str(g[0])
    print("The password is "+str(j))
    Reply
  11. miracleam says

    August 18, 2020 at 1:24 pm

    Wonderful job;
    Greate article ever seen!

    Reply
  12. Psueudo says

    July 11, 2020 at 12:50 am

    Can the function please return a value …

    Reply
  13. pj says

    June 17, 2020 at 1:26 am

    Hi there, thank you for your kind offerings and hard work. Your piece of code is sitting nicely in my program. I am using it to create a random temporary file.
    :¬) pj

    Reply
  14. Sudhir K Singh says

    March 12, 2020 at 1:50 pm

    Nice article on generating random password.

    Reply
    • Vishal says

      March 12, 2020 at 9:38 pm

      Sudhir, I am glad you liked it.

      Reply
  15. Indranil Paul says

    May 6, 2019 at 7:26 pm

    I want to generate a list of 50 proper nouns say country names or fruit names or city names randomly from the list of alphabets provided. The words generated will be meaningful, no random words formed and should not be taken from any predefined list of files. How do I do this? I used ranom word library from PyPi org but the words produced are less common and cannot cluster them in a particular category. How do I achieve this through Python code? Is there a thesaurus or English dictionary library in Python?

    Reply
    • Vishal says

      May 8, 2019 at 8:40 am

      Hey Indranil, You can check this. hope it helps

      https://stackoverflow.com/questions/55073163/english-dictionary-library-in-python3

      https://stackoverflow.com/questions/3788870/how-to-check-if-a-word-is-an-english-word-with-python

      https://pypi.org/project/Vocabulary/https://pypi.org/project/oxforddictionaries/

      Reply
    • Raf says

      May 10, 2019 at 6:03 am

      how can I create Random Password Generator API (8 to 80 characters in length)?

      Reply

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Python Python Random
TweetF  sharein  shareP  Pin

  Python Random Data

  • Guide to Generate Random Data
  • Random randint() & randrange()
  • Random Choice
  • Random Sample
  • Weighted random choices
  • Random Seed
  • Random Shuffle
  • Get Random Float Numbers
  • Generate Random String
  • Generate Secure random data
  • Secrets to Secure random data
  • Random Data Generation Exercise
  • Random Data Generation Quiz

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

Python Basics Python Exercises Python Quizzes Python Interview Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com