Back to Blog
Python

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.

multiline stringstriple quotesf-stringstextwrappython syntax
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:

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, but consistency matters. If your string contains double quotes, use triple single quotes to avoid escaping, and vice versa.

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:

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.

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:

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:

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:

text = """Hello world"""

Another pitfall is mixing quotes. If you start with ''', you cannot include a single quote inside the string without escaping it, even though the string is multiline. The same applies to double quotes. Choose the delimiter that avoids escaping the most common characters in your text.

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:

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 be careful with indentation: the indentation of the expression is part of the string 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.

python multiline string: Practical Usage and Code Examples | RYUSLOG DEV