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 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)

The output of the above code is ?

Random string : p4ylm

Using random.SystemRandom()

For enhanced security, you can use 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)

The output of the above code is ?

Secure random string : K3@mL9$x

Comparison

Method Security Level Best For
random.choices() Basic General purposes, games
secrets Cryptographic Passwords, tokens
SystemRandom() High Security applications

Conclusion

Use random.choices() for basic random strings. For passwords or security tokens, prefer the secrets module for cryptographically secure randomness.

Updated on: 2026-03-15T18:10:30+05:30

724 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements