How can I do a line break (line continuation) in Python (split up a long line of source code)?
Breaking Strings
long_string = (
"This is a very long string that "
"spans multiple lines for readability."
)
long_string = "This is a very long string that " + \
"spans multiple lines for readability."
Implicit Line Continuation
Using parentheses, brackets, or braces allows you to break lines without needing a backslash. This method is preferred for its clarity.
my_list = [
"item1",
"item2",
"item3"
]
Explicit Line Continuation
You can also use a backslash () at the end of a line to indicate that the statement continues on the next line. However, this method is less favored due to potential readability issues.
long_expression = 1 + 2 + 3 + \
4 - 5 * 2