How do you split a long string literal across multiple lines in Python? | A1Lab@MZeeshanM to PythonEnglish • 6 days ago

How do you split a long string literal across multiple lines in Python?

message-square
0

Wrap adjacent string literals inside parentheses (...) (implicit string literal concatenation—the official PEP 8 standard for single-line text split across lines in source code), or use triple quotes ("""...""") when you intentionally want actual newline characters (\n) preserved inside the string value.

Basic Example

# 1. Recommended (PEP 8): Implicit string concatenation inside parentheses
# Produces ONE continuous single-line string with NO embedded newlines
query = (
    "SELECT id, username, email "
    "FROM users "
    "WHERE is_active = TRUE "
    "ORDER BY created_at DESC;"
)
print(query)
# Output: SELECT id, username, email FROM users WHERE is_active = TRUE ORDER BY created_at DESC;

# 2. Triple-quoted string: Preserves literal newline characters (\n) inside the string
multi_line_text = """First line of text
Second line of text
Third line of text"""
print(repr(multi_line_text))
# Output: 'First line of text\nSecond line of text\nThird line of text'

Key Details & Edge Cases

  • Remember trailing/leading spaces with implicit concatenation: Python joins adjacent string literals ("hello" "world") directly with zero separator ("helloworld"). Always include a space at the end of each line ("SELECT id ") or beginning of the next (" FROM users"), or words will glue together ("SELECT idFROM users").
  • Do NOT add commas inside (...): Placing a comma between parenthesized lines (("part 1", "part 2")) turns the expression into a tuple of strings rather than a single concatenated str—one of the most common subtle bugs when refactoring long strings.
  • Mixing f-strings (f"..."), raw strings (r"..."), and standard strings: Each adjacent segment inside parentheses can carry its own prefix independently:
    user_id = 42
    url = (
        "[https://api.example.com/v1/](https://api.example.com/v1/)"
        f"users/{user_id}/"
        r"profile\details"
    )
    
  • Avoid backslash line continuation (\): Ending lines with a trailing backslash ("part 1 " \ / "part 2") works syntactically, but PEP 8 discourages it because a single accidental space after \ causes a SyntaxError, and you cannot place inline # comments on continued lines—whereas parentheses (...) allow inline comments on every line.
  • Clean indentation inside functions with triple-quoted strings (textwrap.dedent): Triple quotes capture leading indentation spaces on lines 2+. Use textwrap.dedent() (with a leading \ to suppress the first empty newline) to write cleanly indented multi-line text inside functions:
    import textwrap
    
    def build_banner() -> str:
        return textwrap.dedent("""\
            Welcome to the service!
            Please check your configuration.
        """)
    

Comparison of Multi-Line String Splitting Methods

Method Syntax Embeds \n Newlines? Allows Inline # Comments? Best Used When
Parentheses Implicit Concatenation ("part 1 " "part 2") No (unless \n written explicitly) Yes Long URLs, SQL queries, regexes, or log/error messages spanning multiple code lines.
Triple Quotes ("""...""") """line 1\nline 2""" Yes (literal line breaks kept) No (# becomes part of string) Email templates, Markdown blocks, docstrings, or multi-line text output.
textwrap.dedent("""\...""") textwrap.dedent("""\...""") Yes (strips shared leading indent) No Multi-line text blocks defined inside indented functions or class methods.
Backslash Continuation (\) "part 1 " \ + newline + "part 2" No No (SyntaxError) Legacy code only—prefer parentheses (...) in modern Python.