PYnative

Python Programming

  • Learn Python
  • Exercises
  • Quizzes
  • Code Editor
  • Tricks
Home » Python » Random » Generate Random Strings and Passwords in Python

Generate Random Strings and Passwords in Python

Updated on: February 16, 2022 | 19 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)

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)

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 ryxay

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)

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)

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)

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#[T

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)

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 vZkOkL97

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

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

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-6cc763dc8806

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=10

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 81OYQ6D430

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

Founder of PYnative.com I am a Python developer and I love to write articles to help developers. Follow me on Twitter. All the best for your future Python endeavors!

Related Tutorial Topics:

Python Python Random

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 10 questions
  • Each Quiz contains 12-15 MCQ
Exercises
Quizzes

Posted 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

All Python Topics

Python Basics Python Exercises Python Quizzes 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.

Explore Python

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

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

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, Cookie Policy, and Privacy Policy.

Copyright © 2018–2023 pynative.com