ansiwrap
ansiwrap provides text wrapping capabilities similar to Python's standard `textwrap` module, but it is specifically designed to correctly handle strings that contain ANSI control sequences for colors and styles. It correctly calculates the effective length of a string by ignoring these non-printable control codes. The latest release is version 0.8.4, published in January 2019, indicating a maintenance-focused or slow release cadence.
Warnings
- breaking ansiwrap version 0.8.4 is not directly compatible with Python 3.12 due to the removal of the `imp` module, leading to `ModuleNotFoundError` during import.
- gotcha The library has not had a new release since January 2019. This suggests it is in maintenance mode or no longer actively developed, which might lead to limited support for newer Python features, potential unaddressed bugs, or future compatibility issues.
- gotcha The example code often relies on an external library like `ansicolors` (or `colors`) to generate ANSI-colored strings. This dependency is not automatically installed with `ansiwrap` and must be installed separately for the quickstart examples to run as shown.
Install
-
pip install ansiwrap
Imports
- fill
from ansiwrap import fill
- shorten
from ansiwrap import shorten
- ansilen
from ansiwrap import ansilen
- strip_color
from ansiwrap import strip_color
Quickstart
from ansiwrap import fill, shorten, ansilen, strip_color
from colors import red, blue, green, color # Requires 'ansicolors' package
s = ' '.join([
red('This string'),
blue('is going on a bit long'),
green('and may need to be'),
color('shortened a bit', fg='purple')
])
print('-- Original string --')
print(s)
print(f'Original length (Python): {len(s)}')
print(f'Printable length (ansiwrap): {ansilen(s)}')
print('\n-- Now filled to 20 columns --')
print(fill(s, 20))
print('\n-- Now shortened / truncated to 20 columns --')
print(shorten(s, 20, placeholder='...'))
print('\n-- Strip colors --')
print(strip_color(s))
print(f'Stripped length: {len(strip_color(s))}')