2025-05-12
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.
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!
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!
I found this especially useful for AI model prompts where clean formatting matters: