Python textwrap Module

In this guide, you'll explore Python's textwrap module for wrapping and formatting text. Learn its functions and examples for better text handling.

The textwrap module in Python provides functions to format and manipulate text by wrapping and filling paragraphs. It is particularly useful for formatting text output, ensuring that lines do not exceed a specified width, and indenting blocks of text.

Table of Contents

  1. Introduction
  2. textwrap Module Functions
    • textwrap.wrap
    • textwrap.fill
    • textwrap.shorten
    • textwrap.dedent
    • textwrap.indent
    • textwrap.TextWrapper
  3. Examples
    • Using wrap
    • Using fill
    • Using shorten
    • Using dedent
    • Using indent
    • Using TextWrapper
  4. Real-World Use Case
  5. Conclusion
  6. References

Introduction

The textwrap module is designed for text formatting and wrapping, which is essential for creating well-formatted console output or preparing text for display. This module provides several convenient functions and a TextWrapper class for advanced text manipulation.

textwrap Module Functions

textwrap.wrap

Wraps the input text into a list of lines, ensuring each line does not exceed the specified width.

import textwrap

wrapped_text = textwrap.wrap("This is a sample text that will be wrapped.", width=10)
print(wrapped_text)

Output:

['This is a', 'sample', 'text that', 'will be', 'wrapped.']

textwrap.fill

Wraps the input text into a single string with lines of the specified width, separated by newline characters.

import textwrap

filled_text = textwrap.fill("This is a sample text that will be wrapped.", width=10)
print(filled_text)

Output:

This is a
sample
text that
will be
wrapped.

textwrap.shorten

Shortens the input text to fit within the specified width, adding an optional placeholder at the end if the text is truncated.

import textwrap

shortened_text = textwrap.shorten("This is a very long text that needs to be shortened.", width=20, placeholder="...")
print(shortened_text)

Output:

This is a very...

textwrap.dedent

Removes any common leading whitespace from every line in the input text.

import textwrap

dedented_text = textwrap.dedent("""
    This is a sample text
    that has some indentation
    that will be removed.
""")
print(dedented_text)

Output:

This is a sample text
that has some indentation
that will be removed.

textwrap.indent

Adds a specified prefix to the beginning of selected lines in the input text.

import textwrap

indented_text = textwrap.indent("This is a sample text.", prefix="> ")
print(indented_text)

Output:

> This is a sample text.

textwrap.TextWrapper

The TextWrapper class provides more control over text wrapping and filling.

Parameters:

  • width: Maximum width of wrapped lines (default: 70).
  • initial_indent: String prepended to the first line of wrapped output.
  • subsequent_indent: String prepended to all lines of wrapped output except the first.
  • expand_tabs: Boolean; if true, tabs will be expanded to spaces (default: True).
  • replace_whitespace: Boolean; if true, all whitespace characters will be replaced by a single space (default: True).
  • drop_whitespace: Boolean; if true, whitespace at the beginning and end of the line after wrapping will be dropped (default: True).
  • fix_sentence_endings: Boolean; if true, ensure that sentence-ending punctuation is followed by two spaces (default: False).
  • break_long_words: Boolean; if true, words longer than the width will be broken (default: True).
  • break_on_hyphens: Boolean; if true, wrapping will occur at hyphens (default: True).
  • tabsize: Size of tab characters (default: 8).

Methods:

wrap

Wraps the input text into a list of lines.

import textwrap

wrapper = textwrap.TextWrapper(width=10)
wrapped_text = wrapper.wrap("This is a sample text that will be wrapped.")
print(wrapped_text)

Output:

['This is a', 'sample', 'text that', 'will be', 'wrapped.']

fill

Wraps the input text into a single string with lines of the specified width.

filled_text = wrapper.fill("This is a sample text that will be wrapped.")
print(filled_text)

Output:

This is a
sample
text that
will be
wrapped.

Examples

Using wrap

import textwrap

wrapped_text = textwrap.wrap("This is a sample text that will be wrapped.", width=10)
print(wrapped_text)

Output:

['This is a', 'sample', 'text that', 'will be', 'wrapped.']

Using fill

import textwrap

filled_text = textwrap.fill("This is a sample text that will be wrapped.", width=10)
print(filled_text)

Output:

This is a
sample
text that
will be
wrapped.

Using shorten

import textwrap

shortened_text = textwrap.shorten("This is a very long text that needs to be shortened.", width=20, placeholder="...")
print(shortened_text)

Output:

This is a very...

Using dedent

import textwrap

dedented_text = textwrap.dedent("""
    This is a sample text
    that has some indentation
    that will be removed.
""")
print(dedented_text)

Output:

This is a sample text
that has some indentation
that will be removed.

Using indent

import textwrap

indented_text = textwrap.indent("This is a sample text.", prefix="> ")
print(indented_text)

Output:

> This is a sample text.

Using TextWrapper

import textwrap

wrapper = textwrap.TextWrapper(width=10)
wrapped_text = wrapper.wrap("This is a sample text that will be wrapped.")
print(wrapped_text)

filled_text = wrapper.fill("This is a sample text that will be wrapped.")
print(filled_text)

Output:

['This is a', 'sample', 'text that', 'will be', 'wrapped.']
This is a
sample
text that
will be
wrapped.

Real-World Use Case

Formatting Console Output

Use textwrap to format console output for better readability.

import textwrap

def format_text(text, width=40):
    return textwrap.fill(text, width=width)

text = "This is a sample text that will be wrapped and formatted to fit a specific width for better readability in the console output."
formatted_text = format_text(text)
print(formatted_text)

Output:

This is a sample text that will be wrapped
and formatted to fit a specific width for
better readability in the console output.

Conclusion

The textwrap module in Python provides essential tools for formatting and wrapping text. Whether you need to ensure that text fits within a specific width, remove leading whitespace, or add prefixes to lines, the textwrap module offers convenient functions and a versatile TextWrapper class to meet your needs.

References

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare