Text Formatting in Python is essential when you want your programs to display output in a clean, structured, and professional way. Whether you are creating reports, formatting console logs, or preparing documentation, Python provides flexible tools for text presentation.
Python’s built-in textwrap
module is one of the most effective ways to format text. It allows you to manage line wrapping, indentation, alignment, and shortening with minimal effort. In this guide, we’ll explore how you can use it, along with other best practices, to format text like a pro.
Table of Contents
Why Use Text Formatting in Python?
Well-structured text is easier to read and understand. Without formatting, long strings often break unpredictably, making reports and logs messy.
With text formatting in Python, you can:
- Wrap long lines into neat blocks of text.
- Control indentation for better structure.
- Shorten or trim text while keeping it meaningful.
- Align content for professional display.
Whether you’re working with console outputs, APIs, or user reports, formatted text ensures clarity and readability.
1. Line Wrapping with wrap()
The wrap()
function in textwrap
breaks long text into a list of wrapped lines, each fitting within a specified width.
import textwrap
sample_text = "Python makes text formatting simple and effective using textwrap."
wrapped_lines = textwrap.wrap(sample_text, width=25)
print(wrapped_lines)
Output:
['Python makes text', 'formatting simple and', 'effective using textwrap.']
This function is ideal for splitting text into multiple lines for structured display.
2. Filling Text with fill()
The fill()
function is similar to wrap()
, but it returns a single string with line breaks, making it convenient for displaying directly.
import textwrap
long_text = """
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Suspendisse dignissim sapien nec erat lacinia, in aliquet
odio feugiat. Nullam eget eros sit amet neque pulvinar.
"""
print(textwrap.fill(long_text, width=40))
Each line will not exceed 40 characters, ensuring your text looks tidy without manual adjustments.
3. Removing Indentation with dedent()
When working with multi-line strings in Python, indentation often sneaks in unintentionally. The dedent()
function removes common leading whitespace.
import textwrap
data = """
This text has
unwanted indentation
from Python code.
"""
print(textwrap.dedent(data).strip())
Output:
This text has
unwanted indentation
from Python code.
This makes your output clean and professional, especially for documentation or formatted reports.
4. Shortening Text with shorten()
The shorten()
function ensures long text fits within a given width while keeping it meaningful.
import textwrap
sentence = "This is a very long sentence that needs trimming."
print(textwrap.shorten(sentence, width=25, placeholder="..."))
Output:
This is a very long...
This is particularly useful for previews, summaries, and UI elements where space is limited.
5. Adding Indentation with indent()
If you want to make text blocks stand out, you can add indentation to each line with indent()
.
import textwrap
code_snippet = "def greet():\n print('Hello, Python!')"
indented = textwrap.indent(code_snippet, prefix=">>> ")
print(indented)
Output:
>>> def greet():
>>> print('Hello, Python!')
This technique is great for formatting code snippets or highlighting text.
6. Custom Indentation with fill()
The fill()
function allows you to define different indentation for the first line and subsequent lines.
import textwrap
msg = "Python gives you full control over how text appears in your output."
formatted = textwrap.fill(
msg,
width=40,
initial_indent=" ",
subsequent_indent=" "
)
print(formatted)
This feature is perfect for creating structured paragraphs, such as in documentation or reports.
7. Advanced Formatting with f-Strings
While textwrap
is powerful, sometimes you need inline text formatting. Python’s f-strings (formatted string literals) make this easy.
name = "Alice"
score = 95.6789
print(f"Student: {name:<10} | Score: {score:.2f}")
Output:
Student: Alice | Score: 95.68
Here, <10
aligns the name within 10 spaces, while .2f
rounds the score to two decimal places. This combination of textwrap
and f-strings provides complete control over text formatting in Python.
Best Practices for Text Formatting in Python
- Keep line width consistent – usually between 40–80 characters for readability.
- Use dedent() for multi-line strings to prevent messy spacing.
- Apply shorten() cautiously – ensure trimmed text still conveys meaning.
- Leverage f-strings for inline formatting of numbers and variables.
- Combine indent() with wrap() or fill() for structured text blocks.
By combining these practices, you’ll ensure your Python output is clean, professional, and easy to read.
Frequently Asked Questions (FAQ)
1. What is Text Formatting in Python used for?
Text Formatting in Python is used to control how strings appear in your program output. It improves readability by wrapping lines, adjusting indentation, aligning text, and trimming long content.
2. Can I use textwrap for multi-line strings?
Yes. The textwrap
module works seamlessly with both single-line and multi-line strings, making it versatile for different use cases.
3. How do I create a hanging indent in Python?
You can set a larger value for subsequent_indent
compared to initial_indent
when using textwrap.fill()
. This creates a hanging indent effect.
4. Is textwrap the only way to format text in Python?
No. Along with textwrap
, you can use f-strings, string formatting (str.format
), and alignment operators for advanced formatting needs.
5. Can I customize the placeholder in shorten()?
Yes. By default, it uses "..."
, but you can pass any string as the placeholder
argument, such as " [more]"
or "-->
.
With these techniques, you now have a complete toolkit for Text Formatting in Python. Whether you’re writing user-facing text, preparing logs, or building structured documents, Python makes formatting clean, consistent, and professional.