在Python中是否可以将一个长行打断成多行

2024-04-20 10:30:48 发布

您现在位置:Python中文网/ 问答频道 /正文

就像C一样,你可以把一条长线分成多条短线。但在Python中,如果我这样做,就会出现缩进错误。。。有可能吗?


Tags: 错误
3条回答

有不止一种方法。

1)。长篇大论:

>>> def print_something():
         print 'This is a really long line,', \
               'but we can make it across multiple lines.'

(第二章)。使用括号:

>>> def print_something():
        print ('Wow, this also works?',
               'I never knew!')

(第三章)。再次使用\

>>> x = 10
>>> if x == 10 or x > 0 or \
       x < 100:
       print 'True'

引用PEP8

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.

如果要将长str赋给变量,可以执行以下操作:

net_weights_pathname = (
    '/home/acgtyrant/BigDatas/'
    'model_configs/lenet_iter_10000.caffemodel')

不要添加任何逗号,否则将得到一个包含许多str的元组!

来自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. 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')

关于二进制运算符周围换行的主题,它接着说:

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.

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 (line breaks before the operator) is suggested.

显式行继续的示例:

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

相关问题 更多 >