random alphanumeric strings
string generation
coding tips
programming
software development

How can I generate random alphanumeric strings?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Generating random alphanumeric strings sounds simple, but the right implementation depends on what the string is for. If the string is a security token, password reset code, or API key, you need a cryptographically secure generator. If it is only for test data or a temporary UI identifier, a simpler pseudo-random generator may be acceptable.

The Safe Default for Tokens: secrets

In Python, the secrets module is the correct default for security-sensitive randomness.

python
1import secrets
2import string
3
4alphabet = string.ascii_letters + string.digits
5token = "".join(secrets.choice(alphabet) for _ in range(16))
6
7print(token)

This creates a 16-character string using uppercase letters, lowercase letters, and digits.

Use this approach for:

  • invitation codes
  • password reset links
  • session-related identifiers
  • anything an attacker should not be able to predict

When random Is Good Enough

If the string is only for simulations, test fixtures, or non-security use cases, random.choice may be fine.

python
1import random
2import string
3
4alphabet = string.ascii_letters + string.digits
5value = "".join(random.choice(alphabet) for _ in range(12))
6
7print(value)

This is simpler for casual use, but it should not be used where predictability matters.

Pick the Alphabet Deliberately

The phrase "alphanumeric" usually means:

  • 'A-Z'
  • 'a-z'
  • '0-9'

In Python, that is:

python
import string

alphabet = string.ascii_letters + string.digits

If you want only lowercase plus digits for user-facing codes, use:

python
alphabet = string.ascii_lowercase + string.digits

That small choice affects readability, collision risk, and user experience when codes are typed manually.

Length and Collision Risk

The longer the string, the lower the chance of accidental collision. A 6-character code is fine for lightweight UI cases, but not for long-lived identifiers in larger systems.

For example:

  • short human-readable codes need usability tradeoffs
  • longer backend tokens need entropy first

So the implementation question is not only "how do I generate it". It is also "how unique and how unpredictable must it be".

A Reusable Helper Function

You can wrap the secure approach in a helper:

python
1import secrets
2import string
3
4def random_alphanumeric(length: int) -> str:
5    alphabet = string.ascii_letters + string.digits
6    return "".join(secrets.choice(alphabet) for _ in range(length))
7
8print(random_alphanumeric(20))

This keeps the call site simple and makes it easy to standardize token generation across a codebase.

When to Use token_urlsafe Instead

If you do not strictly need only letters and digits, secrets.token_urlsafe() is often even better for security-related use because it is built directly for tokens. Use the manual alphabet approach only when the output must be explicitly alphanumeric for compatibility or UX reasons.

User-Facing Codes Need Different Tradeoffs

If humans must read or type the code, you may want to remove ambiguous characters such as O, 0, I, and l. That slightly reduces the alphabet size but makes support and manual entry easier. Security tokens and human-facing invitation codes often need different alphabets even when both are technically random strings.

Common Pitfalls

  • Using the random module for security-sensitive tokens.
  • Calling something "alphanumeric" but accidentally including punctuation.
  • Choosing a short length without thinking about collisions.
  • Reusing one helper for both secure tokens and throwaway test strings without documenting the difference.
  • Assuming random-looking output is automatically unpredictable enough for security use.

Summary

  • Use secrets for security-sensitive alphanumeric strings.
  • Use random only for non-security cases such as test data.
  • Define the alphabet explicitly so the output matches your requirements.
  • Choose length based on collision and predictability needs.
  • Wrap the logic in a helper when the pattern is used repeatedly.

Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.