textwrap3
textwrap3 is a compatibility back-port of Python 3.6's built-in `textwrap` module, providing its features (like `shorten` and `max_lines`) to older Python versions from 2.6 forward. It also includes minor tweaks, particularly around Unicode handling and em-dashes. The current version is 0.9.2, released in January 2019, indicating a maintenance-focused release cadence.
Warnings
- gotcha Due to its design principle, `textwrap3` adheres to Python 3's sensibilities, especially concerning Unicode. It uses `re.UNICODE` and treats Unicode em-dashes like ASCII '--'. This can lead to subtle differences in wrapping behavior compared to the native `textwrap` module in older Python 2.x environments where Unicode handling might differ.
- gotcha The `wrap()` and `fill()` functions, by default, replace all internal whitespace characters (including newlines and tabs) with single spaces before wrapping. Existing newlines in multi-paragraph input will be collapsed. If you need to preserve original newlines as paragraph breaks, process paragraphs separately or use `replace_whitespace=False` (though this might lead to other formatting challenges).
- gotcha For modern Python 3.6+ environments, `textwrap3` is generally unnecessary. All the features it backports are already present in the standard library's `textwrap` module. Installing it in these environments adds an unnecessary dependency.
- gotcha The underlying `textwrap.wrap()` logic (inherited by `textwrap3`) can exhibit poor performance (quadratic time complexity) when wrapping text containing extremely long, unbroken words (e.g., a very long string without spaces or hyphens) if `break_long_words` is `True` (the default).
Install
-
pip install textwrap3
Imports
- wrap
from textwrap3 import wrap
- fill
from textwrap3 import fill
- shorten
from textwrap3 import shorten
- TextWrapper
from textwrap3 import TextWrapper
Quickstart
from textwrap3 import wrap, fill, shorten
long_text = """This is a very long string that needs to be wrapped
into several lines to be more readable. It demonstrates the basic functionality of the textwrap3 library, which is a backport of Python 3.6's textwrap module."""
# Using wrap to get a list of lines
wrapped_lines = wrap(long_text, width=40)
print("Wrapped lines (list):")
for line in wrapped_lines:
print(line)
print("\n" + "-" * 30 + "\n")
# Using fill to get a single string with newlines
filled_text = fill(long_text, width=40)
print("Filled text (single string):")
print(filled_text)
print("\n" + "-" * 30 + "\n")
# Using shorten to truncate text
shortened_text = shorten(long_text, width=50, placeholder=' [...]')
print("Shortened text:")
print(shortened_text)