如何在Python中进行换行(换行)?

问题:如何在Python中进行换行(换行)?

我有一长行代码,我想在多行中分解。我使用什么,语法是什么?

例如,添加一串字符串,

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

并分成两行,如下所示:

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

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'

回答 0

什么线?您只需在下一行就有参数就不会有任何问题:

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

否则,您可以执行以下操作:

if a == True and \
   b == False

查看样式指南以获取更多信息。

从示例行中:

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

要么:

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

请注意,样式指南指出,最好使用带括号的隐式连续符,但是在这种特殊情况下,仅在表达式周围加上括号可能是错误的方法。

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.


回答 1

PEP 8-Python代码样式指南

包装长行的首选方法是在括号,方括号和花括号内使用Python的隐含行连续性。通过将表达式包装在括号中,可以将长行分成多行。应优先使用这些,而不是使用反斜杠进行行连续。

有时反斜杠可能仍然合适。例如,长的多个with语句不能使用隐式连续,因此可以使用反斜杠:

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())

另一种此类情况是使用assert语句。

确保适当缩进续行。绕开二元运算符的首选位置是运算符之后,而不是在运算符之前。一些例子:

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)

现在,PEP8建议数学家及其发布者使用相反的约定(用于在二进制运算处中断)以提高可读性。

唐纳德·克努斯(Donald Knuth)二元运算符垂直对齐之前先断后合的风格,从而减少了确定要添加和减去的项时的工作量。

PEP8:换行符应该在二进制运算符之前还是之后?

唐纳德·克努斯(Donald Knuth)在他的《计算机和排版》系列中解释了传统规则:“尽管段落中的公式总是在二进制运算和关系之后中断,但显示的公式总是在二进制运算和关系之前中断” [3]。

遵循数学的传统通常会导致代码更具可读性:

# Yes: easy to match operators with operands
income = (gross_wages
          + taxable_interest
          + (dividends - qualified_dividends)
          - ira_deduction
          - student_loan_interest)

在Python代码中,只要约定在本地是一致的,就可以在二进制运算符之前或之后中断。对于新代码,建议使用Knuth的样式。

[3]:Donald Knuth的The TeXBook,第195和196页

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. 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.

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)

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?:

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].

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.

[3]: Donald Knuth’s The TeXBook, pages 195 and 196


回答 2

使用反斜杠结束行的危险在于,如果在反斜杠之后添加空格(当然很难看到),则反斜杠将不再执行您原本的想法。

有关更多信息,请参见Python习语和反习语(对于Python 2Python 3)。

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.


回答 3

\在行末放置a 或将语句括在parens中( .. )。从IBM

b = ((i1 < 20) and
     (i2 < 30) and
     (i3 < 40))

要么

b = (i1 < 20) and \
    (i2 < 30) and \
    (i3 < 40)

Put a \ at the end of your line or enclose the statement in parens ( .. ). From IBM:

b = ((i1 < 20) and
     (i2 < 30) and
     (i3 < 40))

or

b = (i1 < 20) and \
    (i2 < 30) and \
    (i3 < 40)

回答 4

您可以在括号和大括号之间打断线。此外,您可以将反斜杠字符附加\到一行以显式中断它:

x = (tuples_first_value,
     second_value)
y = 1 + \
    2

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

从马口中:显式线连接

可以使用反斜杠字符(\)将两条或更多条物理行连接为逻辑行,如下所示:当一条物理行以不属于字符串文字或注释的反斜杠结尾时,则将其与以下行合并成一条逻辑行,删除反斜杠和以下换行符。例如:

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

以反斜杠结尾的行不能带有注释。反斜杠不会继续发表评论。除字符串文字外,反斜杠不会延续令牌(即,字符串文字之外的令牌无法使用反斜杠在物理行之间进行拆分)。反斜杠在字符串文字之外的其他行上是非法的。

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.


回答 6

这可能不是Python的方式,但是我通常使用带有join函数的列表来编写长字符串,例如SQL查询:

query = " ".join([
    'SELECT * FROM "TableName"',
    'WHERE "SomeColumn1"=VALUE',
    'ORDER BY "SomeColumn2"',
    'LIMIT 5;'
])

It may not be the Pythonic way, but I generally use a list with the join function for writing a long string, like SQL queries:

query = " ".join([
    'SELECT * FROM "TableName"',
    'WHERE "SomeColumn1"=VALUE',
    'ORDER BY "SomeColumn2"',
    'LIMIT 5;'
])

回答 7

摘自《 The Hitchhiker’s Guide to Python(Line Continuation)》:

当逻辑代码行长于可接受的限制时,您需要将其划分为多条物理行。如果该行的最后符是反斜杠,则Python解释器将连接连续的行。在某些情况下这很有用,但由于其易碎性通常应避免使用:在反斜杠后的行末添加空格将破坏代码并可能产生意外结果。

更好的解决方案是在元素周围使用括号。在行尾留下未封闭的括号的情况下,Python解释器将加入下一行,直到括号被封闭为止。花括号和方括号的行为相同。

但是,通常情况下,必须分开一条较长的逻辑线表明您正在尝试同时执行太多操作,这可能会影响可读性。

话虽如此,这是一个考虑多次导入的示例(当超出行限制时,在PEP-8上定义),通常也适用于字符串:

from app import (
    app, abort, make_response, redirect, render_template, request, session
)

Taken from The Hitchhiker’s Guide to Python (Line Continuation):

When a logical line of code is longer than the accepted limit, you need to split it over multiple physical lines. The Python interpreter will join consecutive lines if the last character of the line is a backslash. This is helpful in some cases, but should usually be avoided because of its fragility: a white space added to the end of the line, after the backslash, will break the code and may have unexpected results.

A better solution is to use parentheses around your elements. Left with an unclosed parenthesis on an end-of-line the Python interpreter will join the next line until the parentheses are closed. The same behaviour holds for curly and square braces.

However, more often than not, having to split a long logical line is a sign that you are trying to do too many things at the same time, which may hinder readability.

Having that said, here’s an example considering multiple imports (when exceeding line limits, defined on PEP-8), also applied to strings in general:

from app import (
    app, abort, make_response, redirect, render_template, request, session
)

回答 8

如果由于长字符串而要中断行,可以将该字符串分成几部分:

long_string = "a very long string"
print("a very long string")

将被替换

long_string = (
  "a "
  "very "
  "long "
  "string"
)
print(
  "a "
  "very "
  "long "
  "string"
)

两个打印语句的输出:

a very long string

注意情感中的括号。

还要注意,将文字字符串分成几部分,只允许在部分字符串上使用文字前缀:

s = (
  "2+2="
  f"{2+2}"
)

If you want to break your line because of a long literal string, you can break that string into pieces:

long_string = "a very long string"
print("a very long string")

will be replaced by

long_string = (
  "a "
  "very "
  "long "
  "string"
)
print(
  "a "
  "very "
  "long "
  "string"
)

Output for both print statements:

a very long string

Notice the parenthesis in the affectation.

Notice also that breaking literal strings into pieces allows to use the literal prefix only on parts of the string:

s = (
  "2+2="
  f"{2+2}"
)

回答 9

使用行继续运算符,即“ \”

例子:

# Ex.1

x = 1
s =  x + x**2/2 + x**3/3 \
       + x**4/4 + x**5/5 \
       + x**6/6 + x**7/7 \
       + x**8/8
print(s)
# 2.7178571428571425


----------


# Ex.2

text = ('Put several strings within parentheses ' \
        'to have them joined together.')
print(text)


----------


# Ex.3

x = 1
s =  x + x**2/2 \
       + x**3/3 \
       + x**4/4 \
       + x**6/6 \
       + x**8/8
print(s)
# 2.3749999999999996

Use the line continuation operator i.e. “\”

Examples:

# Ex.1

x = 1
s =  x + x**2/2 + x**3/3 \
       + x**4/4 + x**5/5 \
       + x**6/6 + x**7/7 \
       + x**8/8
print(s)
# 2.7178571428571425


----------


# Ex.2

text = ('Put several strings within parentheses ' \
        'to have them joined together.')
print(text)


----------


# Ex.3

x = 1
s =  x + x**2/2 \
       + x**3/3 \
       + x**4/4 \
       + x**6/6 \
       + x**8/8
print(s)
# 2.3749999999999996