Python Practice › Basic Programs › Program 32

Random string of a given length

EasyBasic Programs · 32 of 40

Write a Python program to generate a random string of a specific length.

Advertisement
Input
length = 10
Output
u8jzPde0Ig 10

Approach

  1. Build a pool of characters with the string module.
  2. Pick characters at random and join them.

Solution

Python
import randomimport string random.seed(7)length = 10pool = string.ascii_letters + string.digitspassword = "".join(random.choice(pool) for _ in range(length))print(password, len(password))
Output
u8jzPde0Ig 10

Line by line

Line 6

ascii_letters is a-z and A-Z; adding digits gives 62 possible characters.

Line 7

random.choice picks one character per position and join builds the string.

Tip

For passwords and tokens use the secrets module (secrets.token_urlsafe(16)), which is cryptographically secure. random is fine for test data.

Learn the concept

New to this topic? Read the lesson, then come back.

More basic programs

← All 40 Basic Programs

Leave a Comment