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
Method | Preserves Line Breaks? | Adds \n Automatically? | Use Case |
---|---|---|---|
Triple Quotes | Yes | Yes | Multi-line text (e.g., docstrings, logs) |
Parentheses | No | No | Readable code without literal newlines |
Backslash (\ ) | No | No | Simple line continuation |
Explicit + /\n | Depends on \n usage | No | Dynamic 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!