Use "".join(secrets.choice(string.ascii_uppercase + string.digits) for _ in range(length)) from Python’s built-in secrets and string modules for cryptographically secure IDs, tokens, or codes—or "".join(random.choices(string.ascii_uppercase + string.digits, k=length)) when generating non-security test data or reproducible seeded strings.
Basic Example
import random
import secrets
import string
ALPHABET = string.ascii_uppercase + string.digits # "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" (36 chars)
# 1. Recommended (cryptographically secure): Invite codes, OTPs, API keys, unique IDs
secure_code = "".join(secrets.choice(ALPHABET) for _ in range(12))
print(secure_code)
# Example Output: 'K9P2X7M4Q1W8'
# 2. Fast & reproducible (PRNG): Mock data, synthetic benchmarks, seeded tests
rng = random.Random(42) # Optional local seed for deterministic output
mock_code = "".join(rng.choices(ALPHABET, k=12))
print(mock_code)
# Output: 'W1J8Y4B2R9T5'
Key Details & Edge Cases
- Never use
random.choice()/random.choices()for passwords, reset tokens, or security codes:- The
randommodule uses a deterministic Mersenne Twister pseudorandom generator whose internal state can be reconstructed after observing a sequence of outputs. Always usesecrets.choice()(which draws from your OS CSPRNG viaos.urandom()) for anything security- or collision-sensitive.
- The
- Avoid
random.sample(ALPHABET, k=length)(without replacement):random.sample()picks without replacement, meaning no character can ever appear twice in the same string—reducing entropy and raisingValueError: Sample larger than population or is negativeas soon aslength > 36. Always usesecrets.choice()orrandom.choices()(with replacement).
- Precompute
ALPHABET = string.ascii_uppercase + string.digitsoutside loops:- Concatenating
string.ascii_uppercase + string.digitsonce at module level avoids rebuilding the 36-character string on every call when generating thousands of codes in a batch.
- Concatenating
- Eliminating visually ambiguous characters (
0/O,1/I/L) for human-typed codes:- When generating voucher codes or serial keys that users must type manually, strip lookalike characters from the alphabet:
SAFE_ALPHABET = "".join(c for c in (string.ascii_uppercase + string.digits) if c not in "0O1IL") human_code = "".join(secrets.choice(SAFE_ALPHABET) for _ in range(8))
- When generating voucher codes or serial keys that users must type manually, strip lookalike characters from the alphabet:
- Collision probability (Birthday Paradox) when choosing
length:- With 36 characters ($\approx 5.17$ bits per character), an 8-character string has $36^8 \approx 2.82 \times 10^{12}$ combinations (50% collision chance after ~1.98 million IDs), whereas a 16-character string has $36^{16} \approx 7.95 \times 10^{24}$ combinations. Use at least 12–16 characters for public identifiers.
Comparison of Random Alphanumeric String Generators in Python
| Method | Module | Cryptographically Secure? | Allows Repeated Characters? | Supports Deterministic Seeding? | Best Used When |
|---|---|---|---|---|---|
"".join(secrets.choice(A) for _ in range(n)) (Recommended) |
secrets + string |
Yes (OS CSPRNG) | Yes | No | Security tokens, OTPs, promo codes, session keys, and production IDs. |
"".join(random.choices(A, k=n)) |
random + string |
No (Mersenne Twister) | Yes | Yes (random.Random(seed)) |
Generating synthetic test fixtures, mock datasets, or reproducible benchmarks. |
"".join(random.sample(A, k=n)) (Trap) |
random + string |
No | No (crashes if n > 36) |
Yes | Never for general alphanumeric strings—forbids duplicate letters/digits. |
uuid.uuid4().hex.upper()[:n] |
uuid |
Yes (OS CSPRNG) | Yes | No | Hex-only (0–9, A–F) identifiers (uses only 16 characters, not G–Z). |
You must log in or register to comment.
