How to wrap long text to a specified width in Python

Uses Python's textwrap.fill to wrap a long string to a specified width at word boundaries, preserving readability in console output or logs.

Easy Python 3.9+ Aug 9, 2026 Strings & text 12 views 0 copies

Python code

8 lines
Python 3.9+
import textwrap

text = """This is a long piece of text that definitely exceeds the width limit
if we try to print it on a single line without any wrapping applied."""

wrapped = textwrap.fill(text, width=40)

print(wrapped)

Output

stdout
This is a long piece of text that
definitely exceeds the width limit
if we try to print it on a single
line without any wrapping applied.

How it works

The textwrap.fill() function takes a string and a width and returns a single string with embedded newlines, wrapping at word boundaries. It breaks lines to avoid exceeding the specified width unless a single word is longer than the width. It collapses whitespace and preserves the original text's meaning. This is ideal for formatting output for terminals, logs, or generating readable reports.

Common mistakes

  • Using `textwrap.wrap()` and forgetting to join the resulting list with newlines
  • Not considering that `fill()` collapses multiple whitespace characters
  • Assuming the width includes the current indent or prefix

Variations

  1. Use `textwrap.wrap()` to get a list of lines, then join with `'\n'.join(lines)`
  2. Customize with `initial_indent` or `subsequent_indent` parameters for hanging indents

Real-world use cases

  • Formatting log messages to keep log files readable within a fixed column width.
  • Generating formatted email or report text where lines must not exceed a certain length.
  • Wrapping user-facing help messages in CLI tools to fit the terminal width.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.