Triple quotes are one of Python's simplest and most useful features for working with text. Whether you need a string that spans several lines, want to document a function, or need to embed quotation marks without escape characters, triple quotes handle all of it cleanly. This tutorial walks through every common use case from the ground up.
In Python, you typically create strings using single quotes ('hello') or double quotes ("hello"). Both produce the same result. But when your string needs to contain line breaks, or when it includes a mix of quotation marks, standard quoting gets awkward fast. That is where triple quotes come in. They give you a third way to define strings that handles multiline content and embedded quotes with no extra effort.
What Are Triple Quotes and Why Do They Exist?
A triple-quoted string begins and ends with three consecutive quote characters. Python supports two styles: three single quotes (''') and three double quotes ("""). Both are functionally identical. The string they produce is the same str type you get from regular single or double quotes.
# Triple double quotes
message_a = """This is a triple-quoted string."""
# Triple single quotes
message_b = '''This is also a triple-quoted string.'''
# They produce the exact same result
print(message_a == message_b) # True
The key difference between triple quotes and regular quotes is that triple-quoted strings can span multiple lines. With regular single or double quotes, pressing Enter in the middle of a string causes a SyntaxError. Triple quotes let you include real line breaks directly.
Triple-quoted strings are not comments. The Python interpreter reads them as string literals and creates an object in memory. A true comment in Python uses the # character, which the interpreter ignores entirely.
The other advantage is embedding quotes. Inside a triple double-quoted string, you can freely use single quotes and double quotes without backslash escaping. Inside a triple single-quoted string, the same applies. This makes triple quotes ideal for text that contains dialogue, HTML, JSON, or SQL where quotation marks appear frequently.
# Embedding both quote types without escaping
dialogue = """She said, "I can't believe it's that simple." """
print(dialogue)
Build a valid Python docstring for a function called greet:
Creating Multiline Strings
The primary use of triple quotes is writing strings that span more than one line. Without triple quotes, you would need to insert \n escape characters or concatenate separate strings. Triple quotes let you write the text naturally, and Python preserves every line break exactly as you typed it.
# Without triple quotes — hard to read
menu_old = "Breakfast: eggs\nLunch: sandwich\nDinner: pasta"
# With triple quotes — clear and readable
menu = """Breakfast: eggs
Lunch: sandwich
Dinner: pasta"""
print(menu)
The output of both approaches is identical, but the triple-quoted version is far easier to read in your source code. This matters when you work with longer text blocks such as email templates, help messages, or configuration strings.
If you start your text immediately after the opening """ (on the same line), no leading blank line is added to the string. If you press Enter after the opening quotes, the string begins with a newline character. Place a backslash (\) right after the opening quotes to suppress that leading newline when you want the first line of content on its own line in source code.
# Starts with a blank line (newline after opening """)
with_blank = """
First line
Second line
"""
# No leading blank line (backslash suppresses newline)
no_blank = """\
First line
Second line
"""
print(repr(with_blank))
# '\nFirst line\nSecond line\n'
print(repr(no_blank))
# 'First line\nSecond line\n'
- Multiline
- No (requires \n or concatenation)
- Embedded quotes
- Double quotes free, single quotes need escaping
- Common use
- Short strings, dictionary keys, variable values
- Multiline
- No (requires \n or concatenation)
- Embedded quotes
- Single quotes free, double quotes need escaping
- Common use
- Short strings, text with apostrophes
- Multiline
- Yes (line breaks preserved automatically)
- Embedded quotes
- Both single and double quotes free
- Common use
- Multiline text, docstrings, embedded HTML/SQL/JSON
This code tries to print a multiline greeting. One line has a mistake. Find it.
"" on line 1 to """. Two double quotes open an empty string, not a triple-quoted string. You need exactly three consecutive double quotes to start a multiline string block.
Docstrings: Documenting Your Code
The second major use of triple quotes is writing docstrings. A docstring is a string literal placed as the very first statement inside a function, class, or module. Python attaches it to the object's __doc__ attribute, making it accessible through the built-in help() function and through IDE tooltips.
def celsius_to_fahrenheit(celsius):
"""Convert a temperature from Celsius to Fahrenheit.
Parameters:
celsius (float): Temperature in degrees Celsius.
Returns:
float: Temperature in degrees Fahrenheit.
"""
return celsius * 9 / 5 + 32
# Access the docstring
print(celsius_to_fahrenheit.__doc__)
# Or use the help() function
help(celsius_to_fahrenheit)
PEP 257, the Python docstring conventions guide, recommends using triple double quotes (""") for all docstrings. For a one-liner, keep the opening quotes, text, and closing quotes on the same line. For longer documentation, start with a one-line summary, leave a blank line, then provide detailed descriptions of parameters and return values.
Only the first string literal in a function body becomes the docstring. If you place a second triple-quoted string after it, Python treats it as an unused expression -- it will not appear in __doc__ or in help() output. It is not a comment, just a discarded string.
"Always use triple double quotes around docstrings." — PEP 257, Python Docstring Conventions
How to Write a Multiline String with Triple Quotes in Python
Follow these four steps to create a multiline string using triple quotes. Each step builds on the previous one to produce a complete, working example.
-
Open the triple-quote delimiter
Start your string assignment with three consecutive double quotes (
""") or three consecutive single quotes ('''). Assign it to a variable using the equals sign. For example:address = """ -
Write your text across multiple lines
Type your string content across as many lines as you need. Each line break you enter will be preserved as a newline character in the final string. You can freely include single and double quotes without escaping.
-
Close with the matching triple-quote delimiter
End the string with the same triple-quote style you used to open it. If you opened with
""", close with""". Mismatching (opening with"""and closing with''') will cause aSyntaxError. -
Print or use the result
Pass your variable to
print()to see the multiline output. The string preserves all line breaks and internal whitespace exactly as written between the delimiters.
# Complete example following all four steps
address = """123 Main Street
Apartment 4B
Springfield, IL 62704"""
print(address)
# Output:
# 123 Main Street
# Apartment 4B
# Springfield, IL 62704
Combining Triple Quotes with f-strings and Raw Strings
Triple quotes work with Python's string prefixes. An f prefix turns a triple-quoted string into a multiline f-string, letting you embed variables and expressions inside curly braces. An r prefix creates a raw triple-quoted string where backslashes are treated as literal characters.
Multiline f-strings
name = "Alex"
role = "Developer"
login_count = 47
welcome = f"""Hello, {name}!
Your role: {role}
Total logins: {login_count}"""
print(welcome)
# Output:
# Hello, Alex!
# Your role: Developer
# Total logins: 47
This pattern is common for email templates, CLI output messages, and any situation where you need structured text with dynamic values inserted at runtime.
Raw triple-quoted strings
# Raw string — backslashes stay literal
regex_pattern = r"""
\d{3} # area code
[-.\s]? # optional separator
\d{3} # exchange
[-.\s]? # optional separator
\d{4} # subscriber number
"""
print(regex_pattern)
# The \d and \s remain as literal text, not escape sequences
Raw triple-quoted strings are especially useful for regular expressions and Windows file paths where backslashes are meaningful characters rather than escape sequence markers.
Managing Indentation and Whitespace
One of the most common surprises beginners encounter with triple-quoted strings is unwanted indentation. Because triple quotes preserve whitespace literally, any spaces you add for code readability inside a function or class become part of the string itself.
def get_help_text():
# The 8 spaces of indentation become part of the string
text = """
Usage: app [OPTIONS]
Options:
--help Show this message
--version Show version
"""
return text
print(repr(get_help_text()))
# '\n Usage: app [OPTIONS]\n Options: ...'
Python's standard library provides textwrap.dedent() to solve this. It finds the common leading whitespace across all lines and removes it, so you can indent your triple-quoted strings to match your code structure without polluting the string content.
from textwrap import dedent
def get_help_text():
text = dedent("""\
Usage: app [OPTIONS]
Options:
--help Show this message
--version Show version
""")
return text
print(get_help_text())
# Output starts at column 0 — no extra leading spaces
Notice the backslash after the opening """ in the dedent() example. That suppresses the leading newline so dedent() can calculate indentation correctly. Without it, the first line of the string is empty and the indentation logic may not behave as expected.
Python Learning Summary Points
- Triple quotes (
"""or''') create strings that can span multiple lines and embed both single and double quotation marks without escape characters. - A triple-quoted string placed as the first statement in a function, class, or module becomes a docstring, stored in the
__doc__attribute and accessible throughhelp(). - Triple quotes are string literals, not comments. The interpreter processes them as objects. Use
#for actual comments that the interpreter should ignore. - You can combine triple quotes with the
fprefix for multiline f-strings with variable interpolation, or therprefix for raw strings where backslashes stay literal. - Triple-quoted strings preserve all whitespace, including code indentation. Use
textwrap.dedent()to strip unwanted leading spaces when the string is defined inside indented code. - Place a backslash immediately after the opening triple quotes to suppress a leading blank line in the string content.
Triple quotes are a small feature that saves significant effort across a wide range of Python tasks. Whether you are formatting a help message for a command-line tool, writing clear docstrings for your functions, or embedding a block of HTML in a script, triple-quoted strings keep your code readable and your output clean. Start using them in your next project, and the difference will be immediately apparent.
Frequently Asked Questions
Triple quotes in Python are string delimiters that use three consecutive single quotes (''') or three consecutive double quotes ("""). They allow you to create strings that span multiple lines and contain embedded single or double quote characters without escape sequences.
There is no functional difference. Both produce the same str type and behave identically. PEP 257 recommends triple double quotes for docstrings as a convention, but Python treats the resulting strings as equal.
No. Triple-quoted strings are string literals, not comments. The Python interpreter reads and processes them as string objects. When placed as the first statement in a function, class, or module, they become docstrings. A hash character (#) creates a true comment that the interpreter ignores completely.
Use triple quotes to write a multiline string. Open the string with three quotes (""" or '''), write your text across as many lines as needed, then close with the same three quotes. Line breaks within the triple-quoted block are preserved automatically in the resulting string.
A docstring is a triple-quoted string placed as the very first statement inside a function, class, or module. Python stores it in the object's __doc__ attribute, and tools like help() and IDE tooltips display it automatically. Docstrings serve as built-in documentation for your code.
Yes. Prefix the opening triple quotes with f to create a multiline f-string, such as f"""...""". Variables and expressions inside curly braces will be evaluated and inserted into the string, just like a regular f-string, while preserving the multiline formatting.
Triple-quoted strings preserve all whitespace literally, including the indentation of your source code. If the string is defined inside a function or loop, the leading spaces become part of the string content. Use textwrap.dedent() from Python's standard library to strip the common leading whitespace from every line.
Place a backslash (\) immediately after the opening triple quotes. The backslash escapes the newline character right after the opening delimiter, so the string content starts on the next line without an empty first line.
Yes. Escape sequences like \n, \t, and \\ are processed normally inside triple-quoted strings. If you want to treat backslashes as literal characters, prefix the string with r to create a raw triple-quoted string, such as r"""...""".
While you can place an unassigned triple-quoted string in your code and it will have no visible effect, it is not a true comment. The Python interpreter still creates a string object in memory and then discards it. For commenting code, use the hash character (#) on each line, which the interpreter skips entirely.