Skip to main content

How to Write a Multi-Line String in Python with Triple Quotes

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

A normal string must close on the line where it opens. Text with several lines, such as a message, a template or a prompt for a language model, is easier to read in the code when it looks the way it will print. Three quotes at each end allow exactly that. This guide shows it with a three-line poem, with real output from Python 3.15.2.

Syntax​

Syntax
<name> = """<first line>
<second line>
<last line>"""
PartWhat it means
"""Opens the string; three single quotes, ''', work too
The lines in betweenKept exactly, line breaks included
""" at the endCloses the string. A line break before it would be part of the text

Python's language reference: "Strings can also be enclosed in matching groups of three single or double quotes. These are generally referred to as triple-quoted strings". In them, "Unescaped newlines are also allowed and retained".

Prerequisites​

  • uv and Python. This guide uses uv 0.13.10 with Python 3.15.2, in a project made with uv init.

Step 1: Write the Script​

poem.py
poem = """Roses are red,
violets are blue,
this string has three lines."""

print(poem)

The poem.py script in a macOS-style code window: a triple-quoted string over three lines is assigned to poem and printed.

The closing quotes sit right after lines., so the text doesn't end with an empty line.

Step 2: Run It​

Terminal
uv run python poem.py
Output
Roses are red,
violets are blue,
this string has three lines.

The output in a terminal: the poem printed on three lines exactly as written.

The line breaks typed in the code are in the string.

Common Mistakes​

MistakeWhat happensDo this instead
Forgetting the closing quotesSyntaxError: unterminated triple-quoted string literal (detected at line 1)Close with the same three quotes you opened with
Indenting the lines to match the codeThe spaces become part of the textStart the lines at the left edge, or remove the indent with textwrap.dedent()

Troubleshooting​

SymptomLikely causeFix
The output starts or ends with an empty lineA line break right after the opening """ or before the closing oneStart the text right after """, or end a line with a backslash to drop its line break

FAQ​

Can a triple-quoted string be an f-string?​

Yes: put f before it, as in f"""Hello, {name}""", and the placeholders work on every line.

Is this the same as a docstring?​

A docstring is a triple-quoted string placed first in a function, class or module. The string itself is the same kind.

Conclusion​

Opening and closing with """ kept the poem's three lines and their line breaks exactly as typed, and printing it gave the same three lines.

Additional Resources​