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

新手上路,请多包涵

鉴于:

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

我如何将上面的内容写成两行?

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

原文由 Ray 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 956
2 个回答

什么是线?你可以在下一行有参数没有任何问题:

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

否则你可以这样做:

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

或者使用显式换行符:

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

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

使用括号,您的示例可以写成多行:

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

使用显式换行可以获得相同的效果:

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

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

原文由 Harley Holcombe 发布,翻译遵循 CC BY-SA 4.0 许可协议

来自 _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)file_2.write(file_1.read())
>
> ```

PEP8 现在推荐数学家及其出版商使用的 _相反约定_(用于打破二进制运算)以提高可读性。

Donald Knuth 的 breaking **before** a binary operator 垂直对齐运算符的风格,从而减少了眼睛在确定添加和减去哪些项目时的工作量。

来自 [PEP8: _应该在二元运算符之前还是之后换行?_](http://legacy.python.org/dev/peps/pep-0008/#should-a-line-break-before-or-after-a-binary-operator) :

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

原文由 jfs 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题