Python textwrap.dedent for Clean Multiline Strings

2025-05-12

pythonstd-lib

Python textwrap.dedent for Clean Multiline Strings

Today I learned about textwrap.dedent() which removes leading whitespace from each line of text. Handy anytime you have multiline strings assigned to a variable.

The Problem

When you write multiline strings in Python with proper indentation, you often get unwanted leading whitespace:

def create_prompt():
    prompt = """
        You are a helpful AI assistant.
        Please respond in a friendly tone.
        Keep your answers concise and accurate.
        """
    return prompt

# This includes all the leading spaces!

The Solution: textwrap.dedent()

import textwrap

def create_prompt():
    prompt = textwrap.dedent("""
        You are a helpful AI assistant.
        Please respond in a friendly tone.
        Keep your answers concise and accurate.
        """).strip()
    return prompt

# Clean output without leading whitespace!

Perfect for Model Prompts

I found this especially useful for AI model prompts where clean formatting matters:

Let's Connect

© 2025 Isaac Flath • All rights reserved