There are many situations where you need to generate “random strings” in a program, such as creating test data or issuing temporary session IDs.
In Python, you can easily generate random strings of a specified length and character type by combining the standard random module with the string module, which contains definitions for various character sets.
In this article, I will explain the available constants and provide implementation code.
Table of Contents
- Constants in the
stringmodule - Implementation Example: Generating a temporary access token
- Code Explanation
1. Constants in the string module
The character sets used as “ingredients” for random generation are pre-defined in the string module. There is no need to manually type "abcdef..."; it is common to use the following constants:
| Attribute Name (string module) | Content (Character Set) | Description |
| string.ascii_letters | a-z and A-Z | All alphabet characters (case-sensitive) |
| string.ascii_lowercase | a-z | Lowercase letters only |
| string.ascii_uppercase | A-Z | Uppercase letters only |
| string.digits | 0-9 | Numbers only |
| string.punctuation | !”#$%&… | Symbols only |
2. Implementation Example: Generating a temporary access token
The following code is a function that uses random.choices to generate a random string of a specified length. It implements two patterns: one with letters only, and one with a mix of letters and numbers.
import random
import string
def generate_random_string(length, char_type="alphanumeric"):
"""
Generates a random string with the specified length and character type.
"""
if char_type == "alpha":
# Letters only (a-z, A-Z)
source_chars = string.ascii_letters
elif char_type == "alphanumeric":
# Letters + Digits (a-z, A-Z, 0-9)
source_chars = string.ascii_letters + string.digits
else:
# Default fallback
source_chars = string.ascii_letters + string.digits
# 1. Randomly retrieve characters as a list using random.choices
# k=length specifies the number of characters to retrieve
random_list = random.choices(source_chars, k=length)
# 2. Join the list into a single string
return "".join(random_list)
def main():
# Case 1: Random string with letters only (5 characters)
# Example use: Simple identification code
token_alpha = generate_random_string(5, "alpha")
print(f"Letters only (5 chars): {token_alpha}")
# Case 2: Random string with mixed alphanumerics (12 characters)
# Example use: Session ID or temporary password
token_alphanum = generate_random_string(12, "alphanumeric")
print(f"Alphanumeric (12 chars): {token_alphanum}")
if __name__ == "__main__":
main()
3. Code Explanation
random.choices(population, k=N)
This method was added in Python 3.6. It selects k elements at random from the specified sequence (population) allowing for duplicates (replacement), and returns them as a list.
“”.join(…)
Since the return value of random.choices is a list format like ['a', 'B', 'c'], the join method is used to combine them with an empty string "" to convert it into a single string "aBc".
Important Note
The random module is a pseudo-random number generator and is not cryptographically secure.
For generating actual passwords or security-related tokens, please consider using the secrets module, which has been standard since Python 3.6.
