Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I do a line break (line continuation) in Python?

I have a long line of code that I want to break up among multiple lines. What do I use and what is the syntax?

For example, adding a bunch of strings,

e = 'a' + 'b' + 'c' + 'd' 

and have it in two lines like this:

e = 'a' + 'b' +     'c' + 'd' 
like image 280
Ray Avatar asked Sep 09 '08 23:09

Ray


People also ask

How do you do line continuation in Python?

Use a backslash ( \ ) as a line continuation character In Python, a backslash ( \ ) is a line continuation character. If a backslash is placed at the end of a line, it is considered that the line is continued on the next line.

How do you break a long line into multiple lines in Python?

The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. If necessary, you can add an extra pair of parentheses around an expression, but sometimes using a backslash looks better. Make sure to indent the continued line appropriately.

What is the line continuation character in Python?

The backslash character "\" is used to indicate the line continuation in Python.


1 Answers

What is the line? You can just have arguments on the next line without any problems:

a = dostuff(blahblah1, blahblah2, blahblah3, blahblah4, blahblah5,              blahblah6, blahblah7) 

Otherwise you can do something like this:

if (a == True and     b == False): 

or with explicit line break:

if a == True and \    b == False: 

Check the style guide for more information.

Using parentheses, your example can be written over multiple lines:

a = ('1' + '2' + '3' +     '4' + '5') 

The same effect can be obtained using explicit line break:

a = '1' + '2' + '3' + \     '4' + '5' 

Note that the style guide says that using the implicit continuation with parentheses is preferred, but in this particular case just adding parentheses around your expression is probably the wrong way to go.

like image 113
Harley Holcombe Avatar answered Sep 23 '22 19:09

Harley Holcombe