Python
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax and Data Types
-
Section 3: Collections
-
39: Set Operations: Union, Intersection, Difference
-
Section 4: Control Flow
-
Section 5: Functions
-
Section 6: Turtle Graphics and Early Practice Projects
-
Section 7: Working with Files and I/O
-
Section 8: Regular Expressions
-
Section 9: Object-Oriented Python
-
Section 10: Error Handling
-
Section 11: Modules and Packages
-
Section 12: Iterators, Generators, and Functional Tools
-
Section 13: Decorators and Metaprogramming
-
Section 14: Concurrency and Parallelism
-
Section 15: Working with Dates, Times, and Numbers
-
Section 16: Standard Library Deep Dive I: Data Structures
-
Section 17: Standard Library Deep Dive II: System and Introspection
-
Section 18: Standard Library Deep Dive III: Security and Encoding
-
Section 19: Standard Library Deep Dive IV: Text and Data Utilities
-
Section 20: Networking and Web Basics
-
Section 21: Working with Databases
-
Section 22: Testing and Quality
-
Section 23: Advanced Typing
-
Section 24: Context Managers and Resource Handling
-
Section 25: Text, Unicode, and Binary Data
-
Section 26: More Functional and Iteration Tools
-
Section 27: Data Validation and Configuration
-
Section 28: Working with Images and Media
-
Section 29: Property-Based and Documentation Testing
-
Section 30: Packaging and Deployment
-
Section 31: Performance and Internals
-
Section 32: Design Patterns in Python
-
Section 33: GUI Programming
-
Section 34: Security Basics
-
Section 35: Data Structures and Algorithms
-
Section 36: Practical Projects
-
Section 37: Capstone Projects
-
Section 38: Interview and Algorithm Practice
-
Section 39: Writing Idiomatic Python
325: The textwrap Module for Formatting Output
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.
There are no comments for now.