How do I split the definition of a long string over multiple lines in Python?

In Python, there are several ways to split a long string definition over multiple lines. Here are the most common methods:

1. Triple Quotes (''' or """)

Use triple quotes to preserve literal line breaks in the string:

long_string = """This is a
multi-line string that preserves
line breaks exactly as written."""

Output:

This is a
multi-line string that preserves
line breaks exactly as written.

2. Parentheses for Implicit Concatenation

Wrap the string in parentheses to split it into multiple lines without adding line breaks (automatically concatenated):

long_string = (
    "This is a single-line string split "
    "across multiple lines in code. "
    "No newlines are added in the output."
)

Output:

This is a single-line string split across multiple lines in code. No newlines are added in the output.

3. Backslash (\) for Line Continuation

Use a backslash at the end of a line to continue the string on the next line (no line break added):

long_string = "This is a very long string that \
spans multiple lines using a backslash."

Output:

This is a very long string that spans multiple lines using a backslash.

4. Explicit Concatenation with +

Manually join strings with + (useful for dynamic strings or adding line breaks with \n):

long_string = "This is part 1 of the string. " + \
              "This is part 2. " + \
              "Add line breaks with \n if needed."

5. Combine with \n for Line Breaks

Insert explicit line breaks with \n:

long_string = (
    "Line 1\n"
    "Line 2\n"
    "Line 3"
)

Output:

Line 1
Line 2
Line 3

Key Differences

MethodPreserves Line Breaks?Adds \n Automatically?Use Case
Triple QuotesYesYesMulti-line text (e.g., docstrings, logs)
ParenthesesNoNoReadable code without literal newlines
Backslash (\)NoNoSimple line continuation
Explicit +/\nDepends on \n usageNoDynamic string construction

Example with All Methods

# Triple Quotes
text1 = """Hello,
World!"""

# Parentheses
text2 = ("Hello, "
         "World!")

# Backslash
text3 = "Hello, \
World!"

# Explicit \n
text4 = "Hello,\nWorld!"

All four methods produce the same output:

Hello,
World!

Choose the method that best fits your readability and formatting needs!

Leave a Reply

Your email address will not be published. Required fields are marked *