Skip to Content
Course content

325: The textwrap Module for Formatting Output

Click on the "Edit" button in the top corner of the screen to edit your slide content.

You've probably run into this before: you print a long string to the console, and instead of looking like a clean paragraph, it just stretches across the entire screen, forcing the user to scroll horizontally or making the terminal wrap the text in awkward places that break your words in half. That's where the textwrap module comes in.

How do I stop my long strings from running off the edge of the terminal?

The most common tool you'll use here is textwrap.fill(). It takes a long string and inserts newline characters so that no line exceeds a specific width. I usually set this to around 70 or 80 characters, as that's the "sweet spot" for readability in most terminals.

import textwrap

log_entry = "Station Log: Day 452. The hydroponics bay is experiencing a slight atmospheric leak, but the oxygen scrubbers are compensating. I've notified the engineering team, though they are currently preoccupied with the malfunctioning gravity generator in Sector 7."

# This wraps the text and returns a single string with newlines
formatted_log = textwrap.fill(log_entry, width=50)
print(formatted_log)

If you run that, you'll notice it doesn't just cut the string mid-word. It's smart enough to wrap at the spaces, keeping your words intact.

What is the actual difference between wrap() and fill()?

This confuses people all the time. Honestly, they do the same heavy lifting, but they return different data types. textwrap.wrap() returns a list of strings, where each element is one line. textwrap.fill() returns a single string with \n characters already inserted.

You'll want wrap() if you plan to do something to each line individually—like adding line numbers or putting the text into a GUI list widget.

import textwrap

text = "Python is great for automation, data science, and building web apps."
lines = textwrap.wrap(text, width=20)

for i, line in enumerate(lines, 1):
    print(f"Line {i}: {line}")

My multi-line strings have ugly leading whitespace because of my code's indentation; how do I fix that?

When you use triple-quoted strings inside a function or a class, you usually indent the string so it aligns with your code. The problem is that Python includes those leading spaces in the string itself, which ruins your output formatting.

I use textwrap.dedent() to strip away that common leading whitespace. It looks at all the lines and removes the smallest common amount of indentation from every line.

import textwrap

def print_welcome_message():
    # The spaces before 'Welcome' are part of the string!
    message = """
        Welcome to the Galactic Archive.
        Please enter your credentials.
        Unauthorized access is prohibited.
    """
    print("Without dedent:")
    print(message)
    
    print("\nWith dedent:")
    print(textwrap.dedent(message).strip())

print_welcome_message()

Can I add a prefix or a margin to a whole block of text?

Yes, and you don't have to loop through the lines yourself. textwrap.indent() is perfect for this. It's incredibly useful when you're printing logs or nested data where you want a "block" of text to be shifted to the right.

import textwrap

quote = "The only way to do great work is to love what you do."
# We wrap it first, then indent it
wrapped_quote = textwrap.fill(quote, width=30)
indented_quote = textwrap.indent(wrapped_quote, "    > ")

print(indented_quote)

This makes your output look professional without you having to manually concatenate strings on every single line.




📋 Practical Task

Exercise: Formatting a Galactic Mission Briefing

You are building a terminal-based briefing system for a space crew. You have a raw, indented mission description that looks messy when printed. Your goal is to clean it up and format it for a narrow terminal screen.

Requirements:

  • Start with this raw string inside a function:
    briefing = """
                MISSION: Operation Stardust
                OBJECTIVE: Retrieve the ancient beacon from the ruins of Kepler-186f.
                WARNING: Atmospheric pressure is extreme; ensure all EVA suits are pressurized to 1.2 bar.
            """
            
  • Use textwrap.dedent() to remove the leading indentation from the string.
  • Use textwrap.fill() to ensure the text wraps at a width of 40 characters.
  • Use textwrap.indent() to add the prefix " [!] " to the start of every line in the final output.
  • Print the final result to the console.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.