How to Generate Random Strings in Python: Passwords, Japanese Support, and Examples

目次

1. Introduction

Reasons for Handling Random Strings in Python

In programming, there are surprisingly many situations where you need to generate “random strings.” For example, they are used to automatically generate initial user passwords, create unique identifiers (tokens or IDs), or generate large amounts of test data.

Python is one of the languages that allows you to easily create such random strings with simple code. Even with just the standard library, many methods are available, and you can flexibly choose according to your purpose.

Introducing Practical Knowledge That Even Beginners Can Use with Confidence

In this article, we explain from basic methods to generate random strings in Python, to more advanced and secure methods, and even practical application examples, in an easy-to-understand way.

We also cover methods to generate strings that include not only alphanumeric characters but also Japanese (hiragana, katakana, kanji), and creating dummy data using external libraries.

This content is aimed to be useful not only for Python beginners but also for intermediate users who handle Python in their work.

What You Can Gain from This Article

By reading this article, you can acquire the following skills:

  • Methods to Generate Random Strings Using Python’s Standard Library
  • Best Practices for String Generation Considering Security
  • How to Handle Special Random Strings Including Japanese
  • Methods to Generate Dummy Data Using External Libraries Such as Faker
  • Practical Usage Examples of Random Strings

Now, let’s look at the methods to generate random strings using Python, starting from the basics.

2. Basic Method for Generating Random Strings

Simple Method Using Python’s Standard Library

When generating random strings in Python, the basic approach is the combination of the random module and the string module. These are included in the Python standard library and can be used without any additional installation.

Below is a basic example of generating a random string composed of alphanumeric characters.

import random
import string

def generate_random_string(length=10):
    characters = string.ascii_letters + string.digits
    return ''.join(random.choice(characters) for _ in range(length))

print(generate_random_string())

In this code, it generates a random string of the specified length from a character set combining string.ascii_letters (uppercase and lowercase letters) and string.digits (digits 0-9).

Explanation of Each Component

  • string.ascii_letters: abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ (uppercase and lowercase alphabet)
  • string.digits: 0123456789 (digits)
  • random.choice(): Function to randomly select one item from a list or string, etc.
  • ''.join(...): Joins list elements into a single string

This method is simple and very easy to use, making it suitable for creating lightweight scripts or small utility tools.

Customizable with Any Character Set

Of course, the character set used can be freely customized. For example, it can easily handle cases where you want to use only letters, only numbers, or a character set you define yourself.

def generate_custom_string(length=8):
    characters = 'ABCD1234@#$'
    return ''.join(random.choice(characters) for _ in range(length))

print(generate_custom_string())

Notes on Randomness

The random module used here generates pseudorandom numbers and does not have cryptographic strength. Therefore, in security-sensitive scenarios (such as password generation or API tokens), the secrets module introduced in the next chapter is more suitable.

年収訴求

3. Advanced Random String Generation

Security-Conscious String Generation: secrets Module Utilization

When handling random strings, depending on the use case, strings that are “hard to predict” and “highly secure” may be required. For example, passwords, authentication tokens, API keys, etc.

In Python, the secrets module, which can generate cryptographically secure random numbers, is provided as standard.

import secrets
import string

def generate_secure_string(length=12):
    characters = string.ascii_letters + string.digits
    return ''.join(secrets.choice(characters) for _ in range(length))

print(generate_secure_string())

In this method, instead of the random module, secrets.choice() is used, which internally employs a more secure random number algorithm. For use cases requiring security, always use this one.

Random Strings Including Symbols and Special Characters

When more complex strings are needed, high-strength random strings can be generated by including symbols and special characters (such as !@#%&*).

def generate_complex_password(length=16):
    characters = string.ascii_letters + string.digits + string.punctuation
    return ''.join(secrets.choice(characters) for _ in range(length))

print(generate_complex_password())
  • string.punctuation: !"#$%&'()*+,-./:;<=>?@[]^_{|}~` such as these symbols are included.
  • The output strings have strength equivalent to or greater than password generation tools.

Generating Random Strings Including Japanese (Hiragana, Katakana, Kanji)

There are also cases where you want to handle random strings that include not only alphanumeric characters but also Japanese. For example, when generating test Japanese data.

For Hiragana and Katakana

The following is an example of generating a random string from hiragana.

import random

hiragana = [chr(code) for code in range(12353, 12436) if chr(code).isalpha()]

def generate_hiragana_string(length=8):
    return ''.join(random.choice(hiragana) for _ in range(length))

print(generate_hiragana_string())

In this method, characters are extracted from the Unicode hiragana range (U+3041-U+3096).

For Kanji (With Notes)

Since kanji have a wide Unicode range and are prone to mixing in meaningless characters, it is safer to select from a pre-prepared kanji list as follows.

kanji_list = ['山', '川', '田', '本', '中', '村', '花', '木']

def generate_kanji_string(length=4):
    return ''.join(random.choice(kanji_list) for _ in range(length))

print(generate_kanji_string())

For practical data, it is common to customize based on commercially available lists of common kanji or kanji for names.

Summary: When is Advanced Generation Needed?

Use CasesRecommended ModuleCharacter Types
Automatic Username GenerationrandomAlphanumeric only
Password GenerationsecretsAlphanumeric + Symbols
Test Japanese StringsrandomHiragana, Katakana, Kanji
Tokens, API KeyssecretsHigh-strength Alphanumeric or Custom Set

By selecting modules and character sets according to the purpose, you can generate more secure and practical random strings.

4. Generating Random Data Using External Libraries

Convenient Faker Library for Generating Dummy Data

Python can handle random strings with the standard library as well, but if you want to generate more realistic and meaningful “dummy data (such as fictional names or addresses),” the external library Faker is very convenient.

Faker is a library that randomly generates names, addresses, phone numbers, email addresses, and more, and it is ideal for development, testing, and demo purposes.

How to Install Faker

First, let’s install Faker. Please execute the following command in the terminal.

pip install faker

Basic Usage (English Data)

The following is an example of generating English names and email addresses using Faker.

from faker import Faker

fake = Faker()

print(fake.name())       # Example: John Doe
print(fake.email())      # Example: johndoe@example.com
print(fake.address())    # Example: 1234 Elm Street, Springfield

With this alone, you can quickly create dummy data that looks realistic.

How to Generate Japanese Data?

Faker supports multiple languages, and you can easily generate Japanese data as well. To do so, specify the locale (locale setting) ja_JP.

from faker import Faker

fake = Faker('ja_JP')

print(fake.name())       # Example: Yamada Tarō
print(fake.address())    # Example: 1-2-3 Minami-Aoyama, Minato-ku, Tokyo
print(fake.company())    # Example: Sample Corporation

In this way, you can automatically generate dummy data such as Japanese names and addresses.

Can Faker Also Generate Random Strings?

Yes, Faker has convenient methods such as lexify() and bothify(), allowing you to generate random strings mixing letters and numbers in specific patterns.

print(fake.lexify(text="????-????"))     # Example: xqwe-kdls
print(fake.bothify(text="##??-??##"))    # Example: 45az-kl92
  • ? → Random lowercase letter (a-z)
  • # → Random digit (0-9)

This allows you to easily create structured strings such as “product codes” or “member numbers.”

Bulk Data Generation Using Faker (CSV Save Example)

Faker can easily automatically generate large amounts of dummy data and output it to files such as CSV.

import csv
from faker import Faker

fake = Faker('ja_JP')

with open('dummy_users.csv', 'w', newline='', encoding='utf-8') as file:
    writer = csv.writer(file)
    writer.writerow(['Name', 'Email', 'Address'])

    for _ in range(10):
        writer.writerow([fake.name(), fake.email(), fake.address()])

This code outputs 10 pieces of Japanese user data in CSV format. It is very useful for testing web apps under development, and more.

When Should You Use Faker?

Usage PurposeUsage Examples
Creating Test User DataAutomatically generate names, emails, addresses, etc.
Frontend UI VerificationDisplay lists or tables with fake data
Load Testing or Generating Large Amounts of DataPossible to generate hundreds to tens of thousands in bulk
Building Demo SitesCompliance using non-existent personal information
年収訴求

5. Practical Application Examples

Automatic Generation of Usernames and Initial Passwords

Web services or business applications often issue temporary IDs or initial passwords during user registration. By applying the basics of random string generation, you can automatically and securely generate this information.

import secrets
import string

def generate_user_credentials():
    user_id = ''.join(secrets.choice(string.ascii_lowercase + string.digits) for _ in range(8))
    password = ''.join(secrets.choice(string.ascii_letters + string.digits + string.punctuation) for _ in range(12))
    return user_id, password

user_id, password = generate_user_credentials()
print(f"User ID: {user_id}")
print(f"Initial Password: {password}")

This way, you can easily create duplicate-resistant, strong information.

Use as Test Data

During development, when verifying the operation of forms or databases, you may need dummy names, addresses, product codes, and so on. In such cases, combining the Faker library with methods for generating Japanese strings to batch-generate realistic test data is convenient.

  • User list screen display test
  • Filter function and search function verification
  • Input validation check

Because you can test in a format close to actual operational data, bug detection accuracy improves.

Generating Unique IDs (Tokens, Keys, Identifiers)

For API keys or session IDs issued per user, and other situations where you need “random strings that must not overlap with others”, Python is useful.

import secrets

def generate_token(length=32):
    return secrets.token_hex(length)

print(generate_token())  # Example: '2f6c3b8f2deabfa479b1c61a3e5a9a3f...'
  • secrets.token_hex() generates cryptographically secure hexadecimal strings.
  • It is ideal for generating per-user authentication tokens or API keys.

Also Applicable to Japanese-Language Applications

For example, scripts for randomly generating hiragana and kanji are useful for form tests that require automatic input of names in hiragana or katakana, or for verifying search functions that require kanji input.

import random

katakana = [chr(code) for code in range(12449, 12532) if chr(code).isalpha()]

def generate_katakana_name(length=5):
    return ''.join(random.choice(katakana) for _ in range(length))

print(generate_katakana_name())  # Example: Samyo Tsuhara

Such scripts contribute to quality assurance for both frontend and backend.

Other Uses Like This!

Use CasesSpecific Examples
Programming LearningIdeal for practicing string processing and regular expressions
Game DevelopmentFor character names and code generation
Quizzes and PuzzlesUtilize random strings or patterns in questions
Cryptography ExperimentsVerify combinations with encryption and hashing

6. Summary

The Power to Freely Handle Random Strings in Python

In this article, based on the theme “Python Random Strings,” we covered a wide range from basic generation methods to practical application examples.

Python is a powerful language that can generate random strings simply and flexibly by utilizing both standard and external libraries. By keeping the following points in mind, you can make use of it in many development scenarios.

Reviewing the Points from Each Chapter

  • Basic Generation Methods cover simple methods using the random module and the string module.
  • For security purposes, we explained that the cryptographically secure secrets module is essential.
  • When handling Japanese strings, techniques like using Unicode or predefined lists are effective.
  • By utilizing the Faker library, you can easily generate realistic dummy data such as names, addresses, and emails.
  • In practical applications, we introduced specific examples like user authentication, test data generation, and token issuance.

Notes on Random String Generation

  • The random module is simple but has predictability, so it is inappropriate for security purposes.
  • When generating strings that include symbols or special characters, you need to be mindful of their usage (e.g., situations where URL encoding is required).
  • For random generation of Japanese strings, understand that meaningless strings will be created, and limit it to test purposes as a basic rule.
  • Faker’s data is purely fictional information and has no relation to real people or companies.

Hints for Future Learning

  • Try combining with regular expressions to verify or filter string patterns.
  • Incorporate it into GUI apps or web forms to create string auto-generation features for users.
  • Link it with other libraries (NumPy or Pandas) to build large test datasets.

Random string generation in Python is not just a technique, but can become an important foundational technology that supports various systems and projects. Please make use of what you learned in this article in your own development and learning.

In the next chapter, we will summarize “Frequently Asked Questions (FAQ).” We will carefully answer points that readers are likely to have questions about, so please stick with us until the end.

7. Frequently Asked Questions (FAQ)

This chapter summarizes questions and answers in Q&A format that we often receive from readers when generating random strings in Python.

Q1. What is the difference between the random module and the secrets module?

A1.The random module generates pseudorandom numbers and is suitable for reproducible data or lightweight processing. On the other hand, the secrets module can generate cryptographically secure random numbers and is suitable for uses where security is important, such as passwords or tokens.

ModuleFeaturesMain Uses
randomFast and LightweightTesting and Simple Data Generation
secretsUnpredictablePasswords, API Keys, Authentication Tokens

Q2. Can I create a random string using only specific characters?

A2.Yes, it is possible. For example, by using a custom character set like “ABC123”, you can randomly select characters from it.

import random

chars = 'ABC123'
print(''.join(random.choice(chars) for _ in range(6)))

This is useful for generating product codes or user IDs, etc.

Q3. How do I create random Japanese (hiragana or kanji) strings?

A3.Hiragana and katakana can be easily randomized using Unicode character codes. For kanji, since meaningless characters are likely to mix in, it is safer to select from a pre-prepared list of kanji as shown below.

# Hiragana example
hiragana = [chr(i) for i in range(12353, 12436)]
print(''.join(random.choice(hiragana) for _ in range(5)))

Q4. I want to generate Japanese data with Faker, how can I do that?

A4.Faker supports multiple languages, and to generate Japanese data, simply specify the ja_JP locale.

from faker import Faker

fake = Faker('ja_JP')
print(fake.name())     # Example: Suzuki Tarō

You can automatically generate names, addresses, company names, phone numbers, etc., in Japanese.

Q5. How can I dynamically change the length of the random string?

A5.By passing the length (length) as a function argument, you can generate random strings of any length. The following is a typical example.

def generate_random_string(length=8):
    return ''.join(random.choice('ABC123') for _ in range(length))

print(generate_random_string(12))  # String of length 12

Q6. Is the data generated by Faker from real people?

A6.No, all information such as names and addresses generated by Faker is fictional data. There is no risk of personal information leakage, and it can be safely used for testing or demo purposes.

Q7. Why do I get the same result every time I run it?

A7.By using random.seed() to fix the initial value of the random number, you get reproducible output. Conversely, if you want different results every time, it is common not to specify seed() or to use the system time.

import random
random.seed(42)  # Produces the same result

The above are the common questions and answers when generating random strings in Python.
If you have questions like “Why does this happen?” while practicing, this FAQ will surely be helpful.

RUNTEQ(ランテック)|超実戦型エンジニア育成スクール