Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to break a long line to multiple lines in Python? [duplicate]

Just like C, you can break a long line into multiple short lines. But in Python, if I do this, there will be an indent error... Is it possible?

like image 429
Bin Chen Avatar asked Nov 13 '10 12:11

Bin Chen


People also ask

Is it possible to break a long line to multiple lines in Python?

Breaking Long Lines of Code in Python It is recommended not to have lines of code longer than 79 characters. Python supports implicit line continuation. This means any expression inside the parenthesis, square brackets, or curly braces can be broken into multiple lines.

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

You cannot split a statement into multiple lines in Python by pressing Enter . Instead, use the backslash ( \ ) to indicate that a statement is continued on the next line. In the revised version of the script, a blank space and an underscore indicate that the statement that was started on line 1 is continued on line 2.

How do you split a long line in Python?

To break a line in Python, use the parentheses or explicit backslash(/). Using parentheses, you can write over multiple lines. The preferred way of wrapping long lines is using Python's implied line continuation inside parentheses, brackets, and braces.

How do you break long code lines?

To break a single statement into multiple linesUse the line-continuation character, which is an underscore ( _ ), at the point at which you want the line to break.


1 Answers

From PEP 8 - Style Guide for Python Code:

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.

Example of implicit line continuation:

a = some_function(     '1' + '2' + '3' - '4') 

On the topic of line breaks around a binary operator, it goes on to say:

For decades the recommended style was to break after binary operators. But this can hurt readability in two ways: the operators tend to get scattered across different columns on the screen, and each operator is moved away from its operand and onto the previous line.

In Python code, it is permissible to break before or after a binary operator, as long as the convention is consistent locally. For new code Knuth's style (line breaks before the operator) is suggested.

Example of explicit line continuation:

a = '1'   \     + '2' \     + '3' \     - '4' 
like image 125
Darin Dimitrov Avatar answered Sep 22 '22 15:09

Darin Dimitrov