Welcome, guest | Sign In | My Account | Store | Cart

Generate a password (or other secure token) using a pattern language similar to regular expressions. We'll use the strgen module that enables a user to generate test data, unique ids, passwords, vouchers or other randomized data very quickly using a template language. The template language is superficially similar to regular expressions but instead of defining how to match or capture strings, it defines how to generate randomized strings.

Python, 2 lines
from strgen import StringGenerator as SG

The standard way to create a random string such as for use as a password in Python:

import random
import string
password = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(10))

Using strgen, the equivalent is:

from strgen import StringGenerator as SG

What about the requirement - much more likely - "a password shall have 6 - 20 characters of which at least one must be a digit and at least one must be a special character":


You need to install the module:

pip install strgen

strgen is better than the standard way:

  • Less verbose
  • Trivial editing of the pattern lets you incorporate additional important features (variable length, minimum length, additional character classes, etc.)
  • Uses cryptographic-grade SystemRandom class (if available, or falls back to Random)
  • Uses a pattern language superficially similar to regular expressions, so it's easy to learn
  • Installs with pip

(Disclosure: I am the author of the strgen module.)


Dan Zemke 9 years, 8 months ago  # | flag

Paul - ActiveState's site seems to be doing something with your link to pypi. But a copy/paste of the blue text worked fine.

Paul Wolf (author) 9 years, 8 months ago  # | flag

Fixed the link to PyPi, which is also there: