Python Basics: Formatting Plain Text with textwrap
Readable help messages and short previews make command-line scripts easier to use. Python’s standard-library textwrap module provides a few useful formatting tools.
Use Python 3.12 or newer in Bash on Linux. These independent examples use only in-memory text and do not read or change data files.
Wrap a paragraph
This sample message is narrow enough to show wrapping in a small terminal.
Save as demo_textwrap_1.py:
import textwrap
message = "Check the queue before starting another batch of jobs."
print(textwrap.fill(message, width=24))
print("Lines:", len(textwrap.wrap(message, width=24)))Run it from the directory where you saved it:
python3 demo_textwrap_1.pyOutput:
Check the queue before
starting another batch
of jobs.
Lines: 3fill() returns one string with line breaks. wrap() returns a list of lines. Both handle a single paragraph; wrap separate paragraphs individually when blank lines matter.
By default, long words can be split. To keep identifiers intact, set both break_long_words=False and break_on_hyphens=False; a long identifier can then exceed width.
Remove shared indentation
Triple-quoted strings can carry unwanted indentation from their source code. Here the first line starts immediately after the opening quotes because of the backslash.
Save as demo_textwrap_2.py:
import textwrap
message = """\
Tasks:
check queue
start worker
"""
clean = textwrap.dedent(message)
print(textwrap.indent(clean, "> "), end="")Run it from the directory where you saved it:
python3 demo_textwrap_2.pyOutput:
> Tasks:
> check queue
> start workerdedent() removes the common leading whitespace while preserving relative indentation. Tabs and spaces are distinct, so use consistent indentation. indent() prefixes nonblank lines by default. end="" avoids adding another newline after this string’s existing one.
Make a short preview
Save as demo_textwrap_3.py:
import textwrap
message = " Check the queue before starting another batch. "
preview = textwrap.shorten(message, width=25, placeholder="...")
print(preview)
print("Length:", len(preview))Run it from the directory where you saved it:
python3 demo_textwrap_3.pyOutput:
Check the queue before...
Length: 25shorten() collapses whitespace, then drops words from the end as needed. The placeholder counts toward the width and must fit. This makes a compact preview, but it can omit important details: keep the full message available.
These functions format plain text. They do not preserve Markdown or HTML structure. Choose explicit widths for predictable examples; terminal size and display requirements can vary.
References
Acknowledgements
This post was created with assistance from AI.