How do you spread a long statement over 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. The preferred place to break around a binary operator is after the operator, not before it. Show Example of paranthesized line break: list( "Hello" ) This will give the output: ['H', 'e','l', 'l', 'o'] Example of back-slashed line break: print 'This s a really long line,', \ 'but we can make it across multiple lines.' This will give the output: This is a really long line, but we can make it across multiple lines. Both of these can be used, you may choose to use either depending on which looks more readable to you.
Updated on 30-Sep-2019 08:29:05
From PEP 8 -- Style Guide for Python Code:
PEP8 now recommends the opposite convention (for breaking at binary operations) used by mathematicians and their publishers to improve readability. Donald Knuth's style of breaking before a binary operator aligns operators vertically, thus reducing the eye's workload when determining which items are added and subtracted. From PEP8: Should a line break before or after a binary operator?:
[3]: Donald Knuth's The TeXBook, pages 195 and 196 How do you break a long statement into multiple lines in Python?Break a long line into multiple lines using backslash
According to PEP8 coding convention, each line should be limited to maximum 79 characters for better readability.
How do you write a multiline statement in Python?Multi-line Statement in Python:
In Python, the statements are usually written in a single line and the last character of these lines is newline. To extend the statement to one or more lines we can use braces {}, parentheses (), square [], semi-colon “;”, and continuation character slash “\”.
How do you handle long 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.
How do you continue a long string 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.
|