rstr: Generate Random Strings
rstr is a Python helper module designed for easily generating random strings of various types. It is suitable for applications such as fuzz testing, generating dummy data, or creating random values based on regular expressions. The library is currently at version 3.2.2 and is actively maintained.
Warnings
- gotcha By default, `rstr` uses Python's `random` module (Mersenne Twister), which is a pseudorandom number generator and is NOT cryptographically secure. Do not use default `rstr` for generating sensitive data like passwords or security tokens.
- gotcha The `xeger()` function, which generates strings from regular expressions, can be very slow for complex or ambiguous regex patterns, as it may take a long time to find matching strings.
- gotcha When using `xeger()`, the `*` (zero or more) and `+` (one or more) metacharacters are not truly infinite. They have an arbitrary upper bound of 100 repetitions by default, which might not match expectations for very long strings. The maximum possible is 65535.
- breaking Version 3.0.0 of `rstr` dropped support for Python 2.x. Attempts to use versions 3.x on Python 2.x environments will result in import errors or other incompatibilities.
Install
-
pip install rstr
Imports
- rstr
import rstr
- Rstr
from rstr import Rstr
- xeger
from rstr import xeger
Quickstart
import rstr
from rstr import Rstr, xeger
from random import SystemRandom
# Generate a random string from a custom alphabet
print(f"Random string from 'ABC': {rstr.rstr('ABC')}")
# Generate a fixed-length random string
print(f"4-char string from '0123456789': {rstr.rstr('0123456789', 4)}")
# Generate a random string matching a regex pattern
print(f"Random string matching '[a-z]{{5,10}}': {xeger(r'[a-z]{5,10}')}")
# Use a cryptographically secure random source for sensitive cases
cs_rstr = Rstr(SystemRandom())
print(f"Secure random string (16 hex chars): {cs_rstr.rstr('0123456789abcdef', 16)}")