Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python Multiline String: Syntax and Pitfalls

python multiline string: Learn how to create and manage multiline strings in Python, including triple quotes, indentation handling, f-strings, and common pitfalls.

~4 min readPython
#multiline strings#triple quotes#f-strings#textwrap
Diagram showing triple quotes creating a multiline string in Python code.

Python multiline string syntax uses triple quotes, either three single quotes (''') or three double quotes ("""). This allows you to write strings that span multiple lines without embedding newline characters manually. The newlines in the source code become part of the string value, which is useful for formatting text blocks like SQL queries, JSON snippets, or documentation.

Basic Syntax for Python Multiline Strings

The simplest way to define a multiline string is to enclose it in triple quotes. For example:

python
message = """This is a multiline string. It spans several lines. Each newline is preserved."""

The string message contains the exact text, including the line breaks. Both triple single quotes and triple double quotes work. You do not need to escape individual single or double quotes inside a triple-quoted string, but choose the delimiter that makes the text easiest to read, such as using ''' when the text contains many double quotes or """ when it contains many apostrophes.

python
sql_query = '''SELECT id, name FROM users WHERE active = TRUE'''

The choice between ''' and """ is stylistic, but many style guides recommend """ for docstrings and multiline strings that may contain apostrophes.

How Indentation and Whitespace Are Handled

When you write a multiline string inside a function or class, the indentation in the source code is included in the string. This often produces unexpected leading spaces. Consider:

python
def render(): text = """Line one Line two""" return text

Here, text starts with "Line one" but the second line has four leading spaces because the source code indents the second line. To avoid this, you can either keep the closing quotes at the start of the line, or use textwrap.dedent.

textwrap.dedent removes common leading whitespace from all lines. It is part of the standard library and works well for cleaning up indented blocks.

python
import textwrap def render(): text = textwrap.dedent("""\ Line one Line two """) return text

The backslash at the beginning of the string suppresses the initial newline, and dedent removes the common indentation. This pattern is common in code that embeds SQL or configuration files.

Using Escape Sequences and Raw Multiline Strings

Multiline strings support the same escape sequences as normal strings. For example, you can use \n to force a newline, but that is redundant because the source newline already does that. More useful are \t for tabs and \\ for a literal backslash.

If you need to preserve backslashes exactly, use a raw multiline string by prefixing with r:

python
pattern = r"""\d+\.\d+"""

This is helpful for regular expressions or Windows file paths. Note that a raw string cannot end with an odd number of backslashes, and the triple quotes still work as delimiters.

Common Pitfalls and How to Avoid Them

One frequent mistake is forgetting that the closing triple quotes add a trailing newline if they are on their own line. For example:

python
text = """Hello world """

This string ends with a newline after "world". If you do not want that, place the closing quotes on the same line as the last character:

python
text = """Hello world"""

Another misunderstanding is how quotes work inside triple-quoted strings. You can include individual single or double quotes without escaping: '''She said "hello"''' and """It's ready""" are both valid. The only delimiter issue is a sequence of three consecutive quotes of the same kind as the one used to open the string. Choose the delimiter that makes the text easiest to read.

Indentation issues are also common when building multiline strings dynamically. If you are concatenating parts, consider using join() or parentheses for implicit string concatenation instead of a multiline string, especially when the content is not fixed.

Multiline Strings with F-Strings

Python 3.6 introduced f-strings, which can also be multiline. You can embed expressions inside the braces across lines:

python
name = "Ada" greeting = f"""Hello {name}, Welcome to the team."""

The expression inside {} can span multiple lines if it is enclosed in parentheses, but it is usually clearer to keep expressions short. Multiline f-strings are useful for generating formatted text like emails or reports, but the same indentation rules apply: any indentation in the literal text is preserved unless you use dedent.

Performance and Maintainability Considerations

Multiline strings are immutable, like all Python strings. Creating a large multiline string from a literal is efficient because the compiler stores it as a constant. However, if you build a multiline string by concatenating many pieces, you may incur quadratic time complexity. Use join() for dynamic construction.

For maintainability, multiline strings are ideal for static text that should be readable in the source code. They are less suitable for text that changes frequently or is assembled from user input. In those cases, consider templates or formatting functions.

When storing multiline strings in data structures, be aware that they include newlines and indentation. Use textwrap.dedent or inspect.cleandoc (which also removes leading/trailing blank lines) to normalize content before processing.

A practical approach is to keep multiline strings at module level, outside functions, to avoid indentation issues altogether. If you need to embed a multiline string within a function, always apply dedent and document why.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.