ansiwrap

0.8.4 · maintenance · verified Sun Apr 12

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

Install

Imports

Quickstart

This example demonstrates how to use `ansiwrap` to fill and shorten a string containing ANSI color codes, calculate its effective display length, and strip the colors. It uses the `ansicolors` library to generate the colored text.

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))}')

view raw JSON →