SoFunction
Updated on 2025-03-04

One article will help you master the art of text wrapping of textwrap library in Python

In Python programming, processing text is a basic and common task. Whether it is generating reports, sending emails, or processing user input, text formatting and packaging are indispensable. This is what the textwrap module in the Python standard library is created for, providing a series of simple and powerful tools that help us to elegantly wrap and format text. This article will take you to appreciate the charm of the textwrap library through easy-to-understand language and rich examples.

1. First learn about textwrap

The core function of the textwrap library is to split long text into lines to suit specific width requirements. It provides functions that are simple and easy to use, but can solve many difficult problems in text processing.

import textwrap
 
# Sample texttext = "This is a very long text that needs to be split into multiple lines to suit specific width requirements. The textwrap library can easily accomplish this task."
 
# Use for text wrappingwrapped_text = (text, width=20)
print(wrapped_text)

Run the above code and you will see that the text is automatically split into multiple lines, each line width not exceeding 20 characters. This is the basic usage of functions.

2. The core function of textwrap

The textwrap library contains several core functions, each with its unique purpose. Below we will introduce these functions one by one and show their use through examples.

1. fill

is one of the most commonly used functions, which takes a long text string and a width parameter, splits the text into multiple lines, and returns a new string.

# Example: Use for text wrappinglong_text = "Python's textwrap library provides a range of simple and powerful tools for handling text formatting and wrapping tasks. These tools allow us to easily split long text into lines to suit specific width requirements."
wrapped_text = (long_text, width=30)
print(wrapped_text)

2. wrap

Similar to the fill function, it also accepts a long text string and a width parameter. However, the wrap function returns a list of strings, each element represents a split line.

# Example: Use for text splittingwrapped_lines = (long_text, width=30)
for line in wrapped_lines:
    print(line)

When using wrap function, you can have more flexibility in handling split text lines, such as adding them to different HTML elements, or performing further text processing.

3. dedent

When processing text, you sometimes encounter indentation problems. For example, text read from a file may contain extra spaces or tabs. Functions can remove common prefix spaces (excluding tabs) on each line in the text, making the text cleaner.

# Example: Use Remove Indentationindented_text = """
     This is a text containing redundant indentation.
     Each line has the same space prefix.
     We want to remove these prefixes.
 """
dedented_text = (indented_text)
print(dedented_text)

4. indent

Contrary to dedent, functions can add specified prefixes to each line of text. This is very useful when generating text in a specific format.

# Example: Use the Add Prefixplain_text = "This is the first line.\nThis is the second line."
indented_text = (plain_text, prefix="    ")
print(indented_text)

5. shorten

When working with long text, it is sometimes necessary to shorten it to a specified length and add an ellipsis or other marker at the end. Functions are created for this.

# Example: Use shortened textlong_text = "This is a very long text that needs to be shortened to suit specific length requirements."
shortened_text = (long_text, width=20, placeholder="...")
print(shortened_text)

In this example, the shorten function shortens the long text to 20 characters and adds an ellipsis at the end.

3. Advanced usage and skills

In addition to the above core functions, the textwrap library also provides some parameters and options, allowing us to more refined control of the text wrapping and formatting process.

1. Handle special characters

In text, you sometimes encounter special characters that need to be retained, such as line breaks, tab characters, etc. The textwrap library allows us to control how these characters are processed through parameters.

# Example: Keep newlinestext_with_newlines = "This is the first line.\n\nThis is the second line."
wrapped_text = (text_with_newlines, width=20, replace_whitespace=False)
print(wrapped_text)

In this example, we set the replace_whitespace=False parameter to preserve the newlines in the text.

2. Customize line breaking logic

By default, the textwrap library breaks lines based on spaces and punctuation. But sometimes, we may want to customize the line breaking logic, such as breaking lines at certain specific words. At this time, parameters such as break_long_words and break_on_hyphens can be used.

# Example: Custom line breaking logiclong_word_text = "It's a very long word, it can't be split."
wrapped_text = (long_word_text, width=10, break_long_words=True)
print(wrapped_text)

In this example, we set the break_long_words=True parameter to allow breaking lines inside long words.

3. Custom indentation and prefix

In addition to using the indent function to prefix text, more complex indent and prefix logic can be implemented in fill and wrap functions through the initial_indent and subsequent_indent parameters.

# Example: Custom indentation and prefixtext = "This is a text with multiple paragraphs. Each paragraph should have its own indentation."
wrapped_text = (text, width=30, initial_indent="    ", subsequent_indent="    ")
print(wrapped_text)

In this example, we set the initial_indent and subsequent_indent parameters, adding indents to the first and subsequent lines of the text, respectively.

4. Practical cases

Below, we will use a practical case to show the application of textwrap library in actual projects.

Case: Generate email templates

Suppose we need to generate a mail template with multiple paragraphs, each with specific width and indentation requirements. We can use the textwrap library to do this task easily.

# Email template contentsubject = "Email Subject"
body = """
     Dear customers:
 
     Thank you for choosing our service.  Here are the details of your order:
 
     Order number: 123456
     Order date: 2023-04-01
     Product List:
     - Product A: Quantity 1, price 100 yuan
     - Product B: Quantity 2, price 200 yuan
 
     If you have any questions, please feel free to contact us.
 """
 
# Generate email templates using textwrap librarydef generate_email_template(subject, body, width=60):
    # Process the email text    dedented_body = (body)
    wrapped_body = (dedented_body, width=width, initial_indent="    ", subsequent_indent="    ")
    
    # Build email content    email_template = f"Subject: {subject}\n\n{wrapped_body}"
    return email_template
 
# Generate email templatesemail = generate_email_template(subject, body)
print(email)

In this case, we first define the subject and body content of the email. Then, use the function to remove the excess indentation in the body, then use the function to split the body into multiple lines, and add the specified indentation. Finally, combine the processed body with the topic into a complete email template.

5. Summary

The textwrap library is a very practical text processing tool in the Python standard library. It provides a series of simple and powerful functions that help us easily complete the tasks of text wrapping and formatting. By rationally using functions and parameters in the textwrap library, we can process text data more efficiently and generate text output that meets the requirements. Whether writing code comments, generating report documents, or processing user input and output, the textwrap library provides strong support for us.

The above is a detailed content that will help you master the art of text wrapping in Python. For more information about Python textwrap, please follow my other related articles!