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'
6 个解决方案
#1
893
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
Check the style guide for more information.
查看样式指南以获得更多信息。
From your example line:
从你的例子:
a = '1' + '2' + '3' + \
'4' + '5'
Or:
或者:
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.
注意,样式指南说最好使用带括号的隐式延续,但是在这种情况下,仅仅在表达式周围添加括号可能是错误的。
#2
173
From Style Guide for Python Code:
来自Python代码的样式指南:
The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.
缠绕长线的首选方式是在括号、括号和大括号内使用Python的隐含行延续。通过在括号中包装表达式,可以在多行上分解长行。对于行延续,应该优先使用反斜杠。
Backslashes may still be appropriate at times. For example, long, multiple with-statements cannot use implicit continuation, so backslashes are acceptable:
有时反斜杠还是合适的。例如,长、带-语句的多个语句不能使用隐式延续,所以反斜杠是可以接受的:
with open('/path/to/some/file/you/want/to/read') as file_1, \ open('/path/to/some/file/being/written', 'w') as file_2: file_2.write(file_1.read())
Another such case is with assert statements.
另一种情况是断言语句。
Make sure to indent the continued line appropriately. The preferred place to break around a binary operator is after the operator, not before it. Some examples:
确保适当地缩进连续的行。打破二进制运算符的首选位置是在运算符之后,而不是在它之前。一些例子:
class Rectangle(Blob): def __init__(self, width, height, color='black', emphasis=None, highlight=0): if (width == 0 and height == 0 and color == 'red' and emphasis == 'strong' or highlight > 100): raise ValueError("sorry, you lose") if width == 0 and height == 0 and (color == 'red' or emphasis is None): raise ValueError("I don't think so -- values are %s, %s" % (width, height)) Blob.__init__(self, width, height, color, emphasis, highlight)
EDIT: PEP8 now recommends the opposite convention (for breaking at binary operations) used by Mathematicians and their publishers to improve readability.
编辑:PEP8现在推荐了数学家和他们的出版商使用的相反的惯例(用于二进制运算)来提高可读性。
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.
Donald Knuth所采用的在二进制操作符之前断行的方式,使操作符垂直对齐,从而减少了在确定要添加和删除哪些项时的工作负载。
From PEP8: Should a line break before or after a binary operator?:
从PEP8:一条线应该在二进制运算符之前还是之后中断?
Donald Knuth explains the traditional rule in his Computers and Typesetting series: "Although formulas within a paragraph always break after binary operations and relations, displayed formulas always break before binary operations"[3].
Donald Knuth解释了他的计算机和排版系列中的传统规则:“虽然一个段落中的公式总是在二进制运算和关系之后断掉,但是在二进制运算之前显示的公式总是断掉”[3]。
Following the tradition from mathematics usually results in more readable code:
遵循数学的传统通常会产生更可读的代码:
# Yes: easy to match operators with operands income = (gross_wages + taxable_interest + (dividends - qualified_dividends) - ira_deduction - student_loan_interest)
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 is suggested.
在Python代码中,允许在二进制操作符之前或之后中断,只要约定是本地一致的。对于新代码Knuth的风格建议。
[3]: Donald Knuth's The TeXBook, pages 195 and 196
[3]: Donald Knuth的TeXBook, 195页和196页
#3
59
The danger in using a backslash to end a line is that if whitespace is added after the backslash (which, of course, is very hard to see), the backslash is no longer doing what you thought it was.
使用反斜杠结束一行的危险在于,如果在反斜杠之后添加空格(当然,这是很难看到的),反斜杠将不再执行您认为的操作。
See Python Idioms and Anti-Idioms (for Python 2 or Python 3) for more.
更多信息,请参见Python习语和反习语(用于Python 2或Python 3)。
#4
20
You can break lines in between parenthesises and braces. Additionally, you can append the backslash character \
to a line to explicitly break it:
你可以在括号和括号之间划线。此外,你可以将反斜杠字符\添加到一行中,以显式地破坏它:
x = (tuples_first_value,
second_value)
y = 1 + \
2
#5
19
Put a \
at the end of your line or enclose the statement in parens ( .. )
. From IBM:
在你的行尾放一个\或者用parens (.. .)来自IBM的:
b = ((i1 < 20) and
(i2 < 30) and
(i3 < 40))
or
或
b = (i1 < 20) and \
(i2 < 30) and \
(i3 < 40)
#6
16
From the horse's mouth: Explicit line joining
来自马的嘴:明确的线连接
Two or more physical lines may be joined into logical lines using backslash characters (
\
), as follows: when a physical line ends in a backslash that is not part of a string literal or comment, it is joined with the following forming a single logical line, deleting the backslash and the following end-of-line character. For example:两个或两个以上的物理线路可能会加入到逻辑线路使用反斜杠字符(\)如下:当一个物理行以一个反斜杠,不是字符串或评论的一部分,它是与下面形成一个逻辑行,删除反斜杠和下面的行尾字符。例如:
if 1900 < year < 2100 and 1 <= month <= 12 \ and 1 <= day <= 31 and 0 <= hour < 24 \ and 0 <= minute < 60 and 0 <= second < 60: # Looks like a valid date return 1
A line ending in a backslash cannot carry a comment. A backslash does not continue a comment. A backslash does not continue a token except for string literals (i.e., tokens other than string literals cannot be split across physical lines using a backslash). A backslash is illegal elsewhere on a line outside a string literal.
以反斜线结尾的行不能包含注释。反斜杠不继续注释。反斜杠不继续令牌,除非是字符串(例如。,不能用反斜杠在物理行上分隔符号,而不是字符串。反斜杠在字符串字面上的其他地方是非法的。
#1
893
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
Check the style guide for more information.
查看样式指南以获得更多信息。
From your example line:
从你的例子:
a = '1' + '2' + '3' + \
'4' + '5'
Or:
或者:
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.
注意,样式指南说最好使用带括号的隐式延续,但是在这种情况下,仅仅在表达式周围添加括号可能是错误的。
#2
173
From Style Guide for Python Code:
来自Python代码的样式指南:
The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.
缠绕长线的首选方式是在括号、括号和大括号内使用Python的隐含行延续。通过在括号中包装表达式,可以在多行上分解长行。对于行延续,应该优先使用反斜杠。
Backslashes may still be appropriate at times. For example, long, multiple with-statements cannot use implicit continuation, so backslashes are acceptable:
有时反斜杠还是合适的。例如,长、带-语句的多个语句不能使用隐式延续,所以反斜杠是可以接受的:
with open('/path/to/some/file/you/want/to/read') as file_1, \ open('/path/to/some/file/being/written', 'w') as file_2: file_2.write(file_1.read())
Another such case is with assert statements.
另一种情况是断言语句。
Make sure to indent the continued line appropriately. The preferred place to break around a binary operator is after the operator, not before it. Some examples:
确保适当地缩进连续的行。打破二进制运算符的首选位置是在运算符之后,而不是在它之前。一些例子:
class Rectangle(Blob): def __init__(self, width, height, color='black', emphasis=None, highlight=0): if (width == 0 and height == 0 and color == 'red' and emphasis == 'strong' or highlight > 100): raise ValueError("sorry, you lose") if width == 0 and height == 0 and (color == 'red' or emphasis is None): raise ValueError("I don't think so -- values are %s, %s" % (width, height)) Blob.__init__(self, width, height, color, emphasis, highlight)
EDIT: PEP8 now recommends the opposite convention (for breaking at binary operations) used by Mathematicians and their publishers to improve readability.
编辑:PEP8现在推荐了数学家和他们的出版商使用的相反的惯例(用于二进制运算)来提高可读性。
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.
Donald Knuth所采用的在二进制操作符之前断行的方式,使操作符垂直对齐,从而减少了在确定要添加和删除哪些项时的工作负载。
From PEP8: Should a line break before or after a binary operator?:
从PEP8:一条线应该在二进制运算符之前还是之后中断?
Donald Knuth explains the traditional rule in his Computers and Typesetting series: "Although formulas within a paragraph always break after binary operations and relations, displayed formulas always break before binary operations"[3].
Donald Knuth解释了他的计算机和排版系列中的传统规则:“虽然一个段落中的公式总是在二进制运算和关系之后断掉,但是在二进制运算之前显示的公式总是断掉”[3]。
Following the tradition from mathematics usually results in more readable code:
遵循数学的传统通常会产生更可读的代码:
# Yes: easy to match operators with operands income = (gross_wages + taxable_interest + (dividends - qualified_dividends) - ira_deduction - student_loan_interest)
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 is suggested.
在Python代码中,允许在二进制操作符之前或之后中断,只要约定是本地一致的。对于新代码Knuth的风格建议。
[3]: Donald Knuth's The TeXBook, pages 195 and 196
[3]: Donald Knuth的TeXBook, 195页和196页
#3
59
The danger in using a backslash to end a line is that if whitespace is added after the backslash (which, of course, is very hard to see), the backslash is no longer doing what you thought it was.
使用反斜杠结束一行的危险在于,如果在反斜杠之后添加空格(当然,这是很难看到的),反斜杠将不再执行您认为的操作。
See Python Idioms and Anti-Idioms (for Python 2 or Python 3) for more.
更多信息,请参见Python习语和反习语(用于Python 2或Python 3)。
#4
20
You can break lines in between parenthesises and braces. Additionally, you can append the backslash character \
to a line to explicitly break it:
你可以在括号和括号之间划线。此外,你可以将反斜杠字符\添加到一行中,以显式地破坏它:
x = (tuples_first_value,
second_value)
y = 1 + \
2
#5
19
Put a \
at the end of your line or enclose the statement in parens ( .. )
. From IBM:
在你的行尾放一个\或者用parens (.. .)来自IBM的:
b = ((i1 < 20) and
(i2 < 30) and
(i3 < 40))
or
或
b = (i1 < 20) and \
(i2 < 30) and \
(i3 < 40)
#6
16
From the horse's mouth: Explicit line joining
来自马的嘴:明确的线连接
Two or more physical lines may be joined into logical lines using backslash characters (
\
), as follows: when a physical line ends in a backslash that is not part of a string literal or comment, it is joined with the following forming a single logical line, deleting the backslash and the following end-of-line character. For example:两个或两个以上的物理线路可能会加入到逻辑线路使用反斜杠字符(\)如下:当一个物理行以一个反斜杠,不是字符串或评论的一部分,它是与下面形成一个逻辑行,删除反斜杠和下面的行尾字符。例如:
if 1900 < year < 2100 and 1 <= month <= 12 \ and 1 <= day <= 31 and 0 <= hour < 24 \ and 0 <= minute < 60 and 0 <= second < 60: # Looks like a valid date return 1
A line ending in a backslash cannot carry a comment. A backslash does not continue a comment. A backslash does not continue a token except for string literals (i.e., tokens other than string literals cannot be split across physical lines using a backslash). A backslash is illegal elsewhere on a line outside a string literal.
以反斜线结尾的行不能包含注释。反斜杠不继续注释。反斜杠不继续令牌,除非是字符串(例如。,不能用反斜杠在物理行上分隔符号,而不是字符串。反斜杠在字符串字面上的其他地方是非法的。