Must-Learn for Beginners! Python textwrap Module: Master Python Text Wrapping and Formatting in 3 Minutes
In daily programming, have you encountered these troubles? Text clumping together when generating reports, messy console output, or tedious indentation alignment when writing documents? Actually, Python’s built-in textwrap module can easily solve these problems — it’s like an “automatic formatting assistant” for Python text wrapping. No complex code is needed, and beginners can get started quickly, making text output neat and professional~
Today, we’ll use the easiest-to-understand examples to help you master the core usage of textwrap. You can copy and use it directly after reading!
📏 Basic Operation: Automatic Text Wrapping (Most Commonly Used)
The core function of textwrap is “wrapping text to a specified width”, which is the foundation of Python text wrapping and formatting. It mainly relies on two simple functions: wrap() and fill(). Beginners can handle 80% of text formatting scenarios by mastering these two first~
1. wrap(): Split Text into a List of Wrapped Lines
wrap() is a core function for Python text wrapping. It will split long text into a list of strings according to the set width. Each line will not exceed the specified length, and it will not break in the middle of a word — ensuring clean and readable text formatting~
import textwrap
# Prepare a long text
long_text = "Python is an extremely user-friendly programming language with concise syntax and a particularly rich ecosystem of libraries. textwrap is one of the tools that can quickly beautify text~"
# Split into lines of 20 characters each (supports both Chinese and English)
wrapped_lines = textwrap.wrap(long_text, width=20)
# Print the result (automatic line wrapping for each line)
for line in wrapped_lines:
print(line)
Output:
Python is an extremely
user-friendly programming
language with concise
syntax and a particularly
rich ecosystem of
libraries. textwrap is
one of the tools that
can quickly beautify
text~
2. fill(): Directly Output Formatted String
If you don’t want to handle lists and want to get the complete wrapped text directly, using fill() is more convenient for Python text formatting. Essentially, it’s wrap() + automatic concatenation, directly returning a printable string that’s ready for output~
import textwrap
long_text = "Python is an extremely user-friendly programming language with concise syntax and a particularly rich ecosystem of libraries. textwrap is one of the tools that can quickly beautify text~"
# Format into lines of 30 characters each and output directly
formatted_text = textwrap.fill(long_text, width=30)
print(formatted_text)
Output:
Python is an extremely user-friendly programming
language with concise syntax and a particularly
rich ecosystem of libraries. textwrap is one of
the tools that can quickly beautify text~
Beginner’s Tip: Both functions default to “not breaking words”. They can handle mixed Chinese and English text normally, so you don’t have to worry about messy formatting — a key advantage for Python text wrapping in multi-language scenarios~
Advanced Usage: One-Click Indentation and Unindentation for Python Text Formatting
In addition to basic Python text wrapping, textwrap can also easily handle indentation — a crucial part of text formatting. For example, paragraph indentation when writing reports, or cleaning up indentation of copied code. Beginners can master these advanced text formatting skills in seconds~
1. Custom Paragraph Indentation (initial_indent + subsequent_indent)
Using two parameters of fill(), you can control “first-line indentation” and “subsequent line indentation” respectively, making Python text formatting as standardized as writing an essay. This is especially useful for generating formatted reports or documents~
import textwrap
sample_text = "In programming, text formatting is very important! Whether generating reports or printing prompt messages, neat formatting makes content more readable, and textwrap helps you achieve this easily~"
# First line indented by 2 characters, other lines indented by 4 characters (spaces for indentation)
formatted_text = textwrap.fill(
sample_text,
width=40, # Maximum 40 characters per line
initial_indent=" ", # First line indent: 2 spaces
subsequent_indent=" " # Subsequent lines indent: 4 spaces
)
print(formatted_text)
Output:
In programming, text formatting is very important!
Whether generating reports or printing prompt
messages, neat formatting makes content more
readable, and textwrap helps you achieve this
easily~
2. Clean Up Excess Indentation (dedent())
When copying code or multi-line strings, there are often extra leading spaces. Using dedent() — a handy function for Python text formatting — can clear the common indentation of each line with one click, making the text cleaner and more maintainable~
import textwrap
# Copied code with extra indentation on each line
code = '''
def hello():
print("Hello, textwrap!")
return True
'''
# Clear common indentation
clean_code = textwrap.dedent(code)
print("Cleaned code:")
print(clean_code)
Output:
Cleaned code:
def hello():
print("Hello, textwrap!")
return True
Advanced: Customize Exclusive Python Text Formatting with TextWrapper
If you need more precise control over Python text wrapping and formatting (such as whether to break long words, or whether to wrap at the end of sentences), you can use the TextWrapper class — it’s like customizing “exclusive formatting rules” that can be configured once and used multiple times for consistent text output~
import textwrap
# Create formatting rules (parameters have default values; beginners modify as needed)
wrapper = textwrap.TextWrapper(
width=35, # 35 characters per line
break_long_words=False, # Do not break long words
fix_sentence_endings=True, # Try to wrap at the end of sentences
replace_whitespace=True # Replace extra whitespace characters
)
# Test text
text = "Important Notice: All users are requested to complete the system update before 18:00 next Friday! The system will be unavailable during the update; it is recommended to back up data in advance~"
# Apply formatting rules
formatted_text = wrapper.fill(text)
print(formatted_text)
Output:
Important Notice: All users are requested to
complete the system update before 18:00 next
Friday! The system will be unavailable during
the update; it is recommended to back up data
in advance~
Beginner’s Tip: No need to memorize parameters! For most Python text wrapping and formatting needs, the commonly used ones are width (line width) and break_long_words (whether to break words); keep the others as default~
Beginner’s Practical Combat: 3 High-Frequency Usage Scenarios
After learning the basic usage, let’s see how to use it in actual development. These scenarios are definitely encountered by beginners!
Scenario 1: Format Error Prompt Messages
Make program error messages clearer with Python text formatting so users can quickly understand the problem. Well-formatted error prompts reduce confusion and improve user experience~
import textwrap
def format_error(error_type, msg, suggestion):
# Configure formatting rules: 50 characters per line, subsequent lines indented by 2 spaces
wrapper = textwrap.TextWrapper(width=50, subsequent_indent=" ")
# Format content
formatted_msg = wrapper.fill(msg)
formatted_sug = wrapper.fill(f"Suggestion: {suggestion}")
# Return complete error information
return f"{error_type} Error:\n{formatted_msg}\n{formatted_sug}"
# Use the function
error_info = format_error(
"Type",
"Variable type mismatch; expected string, got integer instead",
"Check the variable type and try again after converting with the str() function"
)
print(error_info)
Output:
Type Error:
Variable type mismatch; expected string, got integer
instead
Suggestion: Check the variable type and try again after
converting with the str() function
Scenario 2: Beautify Docstrings
Automatically wrap the function’s documentation string (docstring) with textwrap for clean Python text formatting, making your code comments look more professional and easier to read~
import textwrap
def calculate_sum(a, b):
"""
This is a sum function that takes two numeric parameters and returns their sum.
Parameters:
a: First number (int/float)
b: Second number (int/float)
Return Value:
Sum of the two numbers (int/float)
"""
# Format the docstring to 40 characters per line
formatted_doc = textwrap.fill(__doc__, width=40)
print(formatted_doc)
return a + b
# Test
calculate_sum(2, 3)
Scenario 3: Console Output Beautification
Use Python text wrapping to make the output text of the program neat and uniform during operation. Beautified console output enhances readability, which is especially useful for displaying logs or user prompts~
import textwrap
# Simulate program running log
log = "Program started successfully! Loading configuration file... Configuration loaded successfully, starting data processing. Data processing progress: 10%→50%→100%, processing successful!"
# Format log to 45 characters per line
formatted_log = textwrap.fill(log, width=45)
print("Program Running Log:")
print(formatted_log)
Output:
Program Running Log:
Program started successfully! Loading configuration
file... Configuration loaded successfully, starting
data processing. Data processing progress:
10%→50%→100%, processing successful!
Beginner’s Summary: Why textwrap is Essential for Python Text Wrapping
- No need to write complex code; Python text wrapping and formatting can be achieved in a few lines with extremely low learning costs;
- Automatically handles Chinese, English, and punctuation, avoiding the embarrassment of “broken words” or “punctuation line breaks”;
- Built-in functions are sufficient for basic Python text formatting scenarios (wrapping, indentation, unindentation), no need to install additional third-party libraries;
- Limitations: Does not support complex formatting such as tables and rich text. For such needs, you can learn specialized formatting libraries later.




