[Python] How to Generate Random Strings (using string module and random.choices)

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

  1. Constants in the string module
  2. Implementation Example: Generating a temporary access token
  3. 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_lettersa-z and A-ZAll alphabet characters (case-sensitive)
string.ascii_lowercasea-zLowercase letters only
string.ascii_uppercaseA-ZUppercase letters only
string.digits0-9Numbers 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.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次