ActiveState Code

Recipe 576722: pseudo-random string


Returns a random, password-suitable string with the specified number of characters. base64 stores 6 bits in each (8-bit) output character, hence the coefficient.

Python
1
2
3
4
import os, math
from base64 import b64encode

randStr = lambda n: b64encode(os.urandom(int(math.ceil(0.75*n))),'-_')[:n]

Sign in to comment