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.
Python code
8 linesimport 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
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
- Use `textwrap.wrap()` to get a list of lines, then join with `'\n'.join(lines)`
- 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
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.