Generate Random Strings in Python
Complete code tutorial with examples and best practices
[ Code Example - Quick Summary ]
Language: Python
What: Generate random strings in Python using the <code>secrets</code> module for cryptographically secure random generation. Perfect for tokens, IDs, and security-sensitive applications.
Try it: Use our interactive Strings generator or integrate this code into your Python application.
Generate random strings in Python using the secrets module for cryptographically secure random generation. Perfect for tokens, IDs, and security-sensitive applications.
Looking for other languages? Check our code examples in
PHP
,
JavaScript
,
Java
,
C#
,
C++
,
Ruby
and
Go
or use our interactive web generator.
Python Code Example
import secrets
import string
def generate_random_string(length=16, custom_chars=None):
if custom_chars is None:
# Default: alphanumeric characters
custom_chars = string.ascii_letters + string.digits
return ''.join(secrets.choice(custom_chars) for _ in range(length))
# Generate a 16-character alphanumeric string
random_string = generate_random_string(16)
print(random_string) # Example: aB3xY7mN2pQ9zR5t
# Generate a 12-character hex string
hex_string = generate_random_string(12, string.hexdigits[:16])
print(hex_string) # Example: a3f7b2e9c4d1
# Generate a 10-character lowercase string
lowercase_string = generate_random_string(10, string.ascii_lowercase)
print(lowercase_string) # Example: xmkpqrstuv
# Generate URL-safe token (alternative method)
url_safe_token = secrets.token_urlsafe(16)
print(url_safe_token) # Example: xK8mP2vN5qR7sT9w
[EXPLANATION]
The secrets module provides cryptographically strong random string generation. secrets.choice() securely selects random characters. The string module provides convenient character sets. For URL-safe tokens, use secrets.token_urlsafe().
Expected Output
aB3xY7mN2pQ9zR5t a3f7b2e9c4d1 xmkpqrstuv xK8mP2vN5qR7sT9w
Common Use Cases
- Django/Flask session token generation
- API key and secret generation
- Database unique identifiers
- File upload temporary names
- CSRF token generation
- Password reset tokens
Important Notes
-
Use
secretsmodule (Python 3.6+) for security -
secrets.token_hex()generates hex tokens -
secrets.token_urlsafe()generates base64url tokens -
Avoid using
randommodule for security purposes
Try Our Interactive Generator
Don't want to write code? Use our free web-based Strings generator with instant results.
TRY STRINGS GENERATOR →Other Programming Languages
View Strings generation code examples in PHP
View Strings generation code examples in JavaScript
View Strings generation code examples in Java
View Strings generation code examples in C#
View Strings generation code examples in C++
View Strings generation code examples in Ruby
View Strings generation code examples in Go