Write multiline strings in Python

Preserve line breaks with triple quotes or split one long logical string across source lines with adjacent literals inside parentheses.

Best practices
Python programming and application logging

Use triple quotes when line breaks belong in the value. To make a long source-code line easier to read without inserting line breaks, put adjacent string literals inside parentheses.

Keep line breaks with triple quotes

text = """First line
Second line
Third line"""
print(text)

Triple-quoted strings retain their newline characters and indentation. They are useful for text blocks, templates, and docstrings. An opening delimiter on a separate line also introduces an initial newline unless you deliberately remove or avoid it.

Split one string across source lines

message = (
    "This message is written across several source lines, "
    "but it becomes one continuous string "
    "without added line breaks."
)

Adjacent literals are concatenated. The indentation between literals is not part of the string; spaces inside the quotes are. Without the explicit spaces at the boundaries, words can run together. This syntax joins literals, not arbitrary variables placed next to one another.

Recognize backslash continuation

A backslash immediately before a physical newline inside an ordinary quoted string removes that newline:

message = "This is one logical line, \
continued here."

Indentation on the continued line becomes part of that string. Backslash-based continuation is easy to damage with trailing whitespace, so parenthesized literals are usually clearer for long strings. Raw-string escape behavior differs; do not generalize this example to every string prefix.

FAQ

How do I remove source indentation from a text block? Use textwrap.dedent() for a common whitespace prefix:

from textwrap import dedent

text = dedent("""\
    First line
    Second line
""")
print(repr(text))  # 'First line\nSecond line\n'

dedent() does not remove all intentional newlines. The backslash after the opening delimiter above avoids the initial newline. Be careful with .strip() if leading or trailing whitespace is meaningful.

Can f-strings span lines? Yes. Use a triple-quoted f-string or adjacent f-strings in parentheses. Each literal that contains replacement fields needs its own f prefix.

Can the text contain quotes? Single and double quote characters can appear inside a triple-quoted string unless they terminate the chosen delimiter. Escape a conflicting delimiter sequence or choose the other quote style.

References

Get a tailored plan

Contact us

Join the community

Scan with WeChat
to join the community

Try Guance

Start online and pay only for what you use.

Get started

Choose a Guance plan

Code hosting