Skip to content

Module 7 · Strings — topic 22 of 22

Multiline strings

Write text that spans several lines with triple quotes, implicit concatenation or join(). Learn how indentation and the first newline behave, textwrap.dedent(), and when each technique fits.

Beginner 10 min read·Lesson 103 of 306 in Python Programming

Learning objectives

  • Create multi-line text with triple quotes
  • Control indentation with textwrap.dedent()
  • Build long strings across lines with parentheses

Definition

Write text that spans several lines with triple quotes, implicit concatenation or join(). Learn how indentation and the first newline behave, textwrap.dedent(), and when each technique fits.

Introduction

Some text naturally has several lines: an address, an email template, a help message, a block of SQL. Python offers a few ways to write it so the code stays readable and the output looks right.

Why it matters

Long text written as one line is hard to edit, and text built with many \n escapes is hard to read. Choosing the right multi-line technique keeps templates easy to maintain and avoids stray spaces and blank lines in the output.

Detailed explanation

Multi-line strings are often templates that will later be filled with data. Keeping such templates in one place, for example as constants at the top of a module or in separate text files, makes them easy for non-programmers to review and edit without touching the program logic.

Triple-quoted strings ("""...""") keep every character between the quotes, including line breaks and leading spaces.

A newline right after the opening quotes becomes part of the string. Start the text on the same line, or put a backslash right after the opening quotes, or call .strip(), to avoid a leading blank line.

Indentation inside a function is also kept. textwrap.dedent() removes the common leading spaces so you can indent the literal with the code.

Implicit concatenation: adjacent string literals inside parentheses are joined into one string without line breaks, which suits long single-line messages.

"\n".join(lines) builds multi-line text from a list, ideal when lines come from data.

A backslash at the end of a code line continues the statement, but parentheses are clearer and less error-prone.

Syntax

Python
text = """First line
Second line"""
message = (
"part one, "
"part two"
)
body = "\n".join(lines)
  • Triple quotes keep line breaks.
  • Adjacent literals in parentheses join without breaks.
  • join() builds text from a list of lines.

Code examples

Triple quotes

Python
address = """KENHOLT Skills
2nd Floor, Tech Park
Bengaluru 560001"""
print(address)
print(address.count("\n") + 1, "lines")
Output
KENHOLT Skills
2nd Floor, Tech Park
Bengaluru 560001
3 lines

The leading newline

Python
a = """
Hello"""
b = """\
Hello"""
print(repr(a), repr(b))
Output
'\nHello' 'Hello'

More examples

A template inside a function

Python
import textwrap
def welcome_email(name, plan):
body = textwrap.dedent(f"""\
Hi {name},
Welcome to the {plan} plan.
- Lessons: all modules
- Support: weekdays
Happy learning!""")
return body
print(welcome_email("Asha", "Pro"))
notice = (
"Classes start on 22 November. "
"Please join five minutes early."
)
print(notice)
Output
Hi Asha,

Welcome to the Pro plan.
  - Lessons: all modules
  - Support: weekdays
Happy learning!
Classes start on 22 November. Please join five minutes early.

Step-by-step explanation

  • The backslash after the opening quotes stops the string from starting with a newline.
  • The template is indented to match the function, and dedent removes the common 8 spaces.
  • Lines indented further keep their extra 2 spaces, so the list items stay indented.
  • The notice is two adjacent literals inside parentheses, joined into one line.

Expected output

Running “A template inside a function” prints exactly:

TextOutput
Hi Asha,
Welcome to the Pro plan.
- Lessons: all modules
- Support: weekdays
Happy learning!
Classes start on 22 November. Please join five minutes early.

Practical applications

  • Email and SMS templates are stored as multi-line strings.
  • Command-line tools print usage help from a triple-quoted string.
  • Database code embeds SQL queries in triple-quoted strings.

Best practices

  • Use triple quotes for genuinely multi-line text.
  • Use dedent for templates inside functions.
  • Use parentheses with adjacent literals for long single-line text.

Common mistakes

Unwanted indentation in output

Avoid

def f():
return """
line one
line two"""

Prefer

def f():
return textwrap.dedent("""\
line one
line two""")

Triple-quoted strings keep the code’s indentation unless you dedent them.

Missing space between joined literals

Avoid

("Classes start soon."
"Join early.")

Prefer

("Classes start soon. "
"Join early.")

Implicit concatenation adds no space; include it at the end of the first piece.

Key takeaways

  • Triple-quoted strings keep line breaks and indentation.
  • textwrap.dedent removes common leading spaces.
  • Adjacent literals in parentheses join without a newline.

Try it yourself

  1. 1
    Write a function that returns a three-line receipt header using a dedented triple-quoted f-string.
  2. 2
    Split a long error message across two code lines using parentheses so it prints on one line.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
Practise this topic