是否可以在Python中将多行换成多行? [英] Is it possible to break a long line to multiple lines in Python?

查看:48
本文介绍了是否可以在Python中将多行换成多行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就像C一样,您可以将一条长线分成多条短线.但是在 Python 中,如果这样做,将会出现缩进错误.可能吗?

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?

推荐答案

来自 PEP 8-Python代码样式指南:

包裹长行的首选方法是使用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.

隐式连续行的示例:

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.

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

显式连续行的示例:

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

这篇关于是否可以在Python中将多行换成多行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆