How can I do a line break (line continuation) in Python?
In Python, you can use the "" character to indicate a line continuation.
In Python, you can use the \ character to indicate a line continuation. For example:
Using the backslash () for line continuation
x = 1 + 2 + 3 + \
4 + 5 + 6
print(x)You can also use parentheses, brackets, or braces to indicate a line continuation. For example:
Implicit line continuation with parentheses, brackets, or braces
x = (1 + 2 + 3 +
4 + 5 + 6)
y = [1, 2, 3,
4, 5, 6]
z = {1: "one",
2: "two"}
print(x)
print(y)
print(z)
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Python - The Practical Guide</div>
You can also separate multiple statements on a single line using a semicolon (;). Note that this acts as a statement separator, not a line continuation operator, and does not join lines into a single logical statement.
Separating multiple statements on one line
x = 1 + 2 + 3 ; print(x)For multi-line strings, you can use triple quotes (""" or '''). This preserves line breaks within the string literal rather than serving as a general code continuation method.
Creating multi-line strings with triple quotes
x = """
This is a
multi-line string
"""
print(x)