Braceexpand
Braceexpand is a Python library that implements Bash-style brace expansion, allowing for the generation of arbitrary strings based on patterns. It provides an iterator over expanded strings, supporting integer ranges, character ranges, sequences, and nested patterns. The current version is 0.1.7, and it is compatible with Python 2.7 and 3.6+. While it closely mimics Bash behavior, it has a slower release cadence, with the last major update to 0.1.7 being in May 2021.
Warnings
- breaking Unlike Bash, a pattern containing unbalanced braces will raise an `UnbalancedBracesError` exception. Bash would typically partly expand or ignore such patterns.
- gotcha Mixed-case character ranges like `{Z..a}` or `{a..Z}` will not include the characters `[]^_`` between 'Z' and 'a' in ASCII order. This differs from some Bash environments.
- gotcha The `braceexpand` function returns an iterator, not a list. If you need all expanded strings at once, you must explicitly convert the iterator to a list (e.g., `list(braceexpand(...))`).
- gotcha Performance may be an issue for very large datasets. The library is not designed for high-performance scenarios with extensive expansions.
- gotcha The backslash (`\`) is the default escape character. If you want to expand patterns containing literal backslashes or disable escaping, you need to use raw strings and/or set `escape=False`.
Install
-
pip install braceexpand
Imports
- braceexpand
from braceexpand import braceexpand
- UnbalancedBracesError
from braceexpand import UnbalancedBracesError
Quickstart
from braceexpand import braceexpand
# Example 1: Integer range
expanded_items = list(braceexpand('item{1..3}'))
print(f"Integer range: {expanded_items}")
# Example 2: Character range
expanded_chars = list(braceexpand('{a..c}'))
print(f"Character range: {expanded_chars}")
# Example 3: Sequence expansion
expanded_files = list(braceexpand('index.html{,.backup}'))
print(f"Sequence expansion: {expanded_files}")
# Example 4: Nested patterns
expanded_versions = list(braceexpand('python{2.{5..7},3.{2,3}}'))
print(f"Nested patterns: {expanded_versions}")
# Example 5: Handling unbalanced braces (raises an exception)
from braceexpand import UnbalancedBracesError
try:
list(braceexpand('{1{2,3}'))
except UnbalancedBracesError as e:
print(f"Caught expected error: {e}")