Python Practice › Basic Programs › Program 32
Random string of a given length
Write a Python program to generate a random string of a specific length.
Input
length = 10
Output
u8jzPde0Ig 10
Approach
- Build a pool of characters with the
stringmodule. - Pick characters at random and join them.
Solution
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.