Line continuation | Long statement in Multiple lines in Python

In this article, we will see how to do line continuation when we write a statement or code a long string in python.

In python, we cannot split a line into multiple lines using Enter. Instead, we have to use the backslash () to tell python that the next line continues in a new line.

So to let a long string continue on the next line in python, we can

  1. Use a backslash , or
  2. Use parentheses ()

Let’s understand it with some examples.

Using backslash for line continuation in Python

The backslash () is the line continuation operator, it tells python that the statement is split into multiple lines. To write the long statement into multiple lines we have to add the backslash at the end of each line.

If we use Enter to go to the next line, it will throw us an error when we run the program.

For example, if we have a long string split into multiple lines using Enter.

str = "Hello, i am a coder
I like to write  code in python
Thank you
"

print(str)

Now, when we run the program we get the following output.

File "main.py", line 1
  str = "Hello, i am a coder
                            ^
SyntaxError: EOL while scanning string literal

It throws us the “EOL while scanning string literal” error.

To fix this we can use the backslash at the end of each line. For example.

str = "Hello, i am a coder 
I like to write  code in python 
Thank you 
"

print(str)

Now when we run the program, we get

Hello, i am a coder I like to write  code in python Thank you

Here, because of at the end of each line, python treats the sentence of each line as one.

We can also use it with integers too for calculation.

add_num = 2+
3+
4

print(add_num)

The output will be the sum of all the numbers.

9

Using parentheses for line continuation

In python, we can also create a multiline statement using parentheses. We can wrap the statement within the parentheses () to split the statement into multiple lines.

Here, each line should be inside the single (' ') and double quotation mark (" ").

For example.

str = ("Hello, i am a coder " 
"I like to write  code in python " 
"Thank you")

print(str)

So the output of the program will be.

Hello, i am a coder I like to write  code in python Thank you

The parentheses tell python to print the whole sentence in one line and not to treat it as a multi-line string.

Conclusion:

Here, we learned about two methods to do line continuation in python using the backslash and parentheses.

Scroll to Top