Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Generate random string of given length
In this article we will see how to generate a random string with a given length. This will be useful in creating random passwords or other programs where randomness is required.
Using random.choices()
The choices() function in the random module can produce multiple random characters which can then be joined to create a string of given length ?
Example
import string
import random
# Length of string needed
N = 5
# With random.choices()
res = ''.join(random.choices(string.ascii_letters + string.digits, k=N))
# Result
print("Random string :", res)
The output of the above code is ?
Random string : nw1r8
Using secrets Module
The The output of the above code is ? For enhanced security, you can use The output of the above code is ? Use secrets module provides cryptographically secure random generation. It has a choice()
Example
import string
import secrets
# Length of string needed
N = 5
# With secrets.choice()
res = ''.join(secrets.choice(string.ascii_lowercase + string.digits)
for i in range(N))
# Result
print("Random string :", res)
Random string : p4ylm
Using random.SystemRandom()
SystemRandom() which uses the operating system's randomness source ?Example
import string
import random
# Length of string needed
N = 8
# Using SystemRandom for cryptographic use
secure_random = random.SystemRandom()
characters = string.ascii_letters + string.digits + string.punctuation
res = ''.join(secure_random.choice(characters) for i in range(N))
print("Secure random string :", res)
Secure random string : K3@mL9$x
Comparison
Method
Security Level
Best For
random.choices()Basic
General purposes, games
secretsCryptographic
Passwords, tokens
SystemRandom()High
Security applications
Conclusion
random.choices() for basic random strings. For passwords or security tokens, prefer the secrets module for cryptographically secure randomness.
