首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python、PEP-8、E122连续行缺少缩进或缩进

Python、PEP-8、E122连续行缺少缩进或缩进
EN

Stack Overflow用户
提问于 2015-10-15 19:40:34
回答 5查看 24.5K关注 0票数 10

我得到了这个错误,但无论我如何选择缩进,我仍然得到它,你知道为什么吗?

代码语言:javascript
复制
if len(argmaxcomp) == 1:
    print "The complex with the greatest mean abundance is: {0}"\
    .format(argmaxcomp[0])
EN

回答 5

Stack Overflow用户

发布于 2015-10-17 01:01:48

通常,pep8建议您使用prefer parenthesis over continuation lines

PythonPython行换行的首选方法是在圆括号、括号和括号中使用

隐含的行续行。通过将表达式放在圆括号中,可以将长行换成多行。应该优先使用它们,而不是使用反斜杠作为行续行符。

这就是:

代码语言:javascript
复制
if len(argmaxcomp) == 1:
    print("The complex with the greatest mean abundance is: {0}"
          .format(argmaxcomp[0]))

另一种选择是使用python 3的print:

代码语言:javascript
复制
from __future__ import print_function

if len(argmaxcomp) == 1:
    print("The complex with the greatest mean abundance is:", argmaxcomp[0])

注意: print_function可能会中断/需要更新其余代码...任何你使用过打印的地方。

票数 8
EN

Stack Overflow用户

发布于 2015-10-15 19:49:59

有一个one section in the PEP8是这样写的:

PythonPython行换行的首选方法是在圆括号、括号和括号中使用

隐含的行续行。通过将表达式放在圆括号中,可以将长行换成多行。应该优先使用它们,而不是使用反斜杠作为行续行符。

反斜杠有时可能仍然是合适的。例如,long、multiple with -statements不能使用隐式延续,因此可以使用反斜杠

这意味着(即使这与PEP8-E122无关),您应该将其括在括号中,而不是使用反斜杠,然后隐式的行续行(缩进)是开始括号:

代码语言:javascript
复制
if len(argmaxcomp) == 1:
    print("The complex with the greatest mean abundance is: {0}"
          .format(argmaxcomp[0]))
#         ^--------- The bracket opens here

这里只提到了两个例外,反斜杠是可以接受的,因为括号是不可能的(因为它们在这些上下文中有另一种含义):

  • multi-with
  • asserts

但是,如果你真的想要反斜杠(只有python2才能做到),它的缩进应该与第一个表达式相同::

代码语言:javascript
复制
if len(argmaxcomp) == 1:
    print "The complex with the greatest mean abundance is: {0}" \
          .format(argmaxcomp[0])
#         ^--------- The first expression starts here
票数 0
EN

Stack Overflow用户

发布于 2015-10-15 19:51:56

这种情况下的问题是根本没有缩进,显然错误发生在最后一行。如果括号不是一个选项,只需添加缩进,如下所示:

代码语言:javascript
复制
if len(argmaxcomp) == 1:
    print "The complex with the greatest mean abundance is: {0}" \
        .format(argmaxcomp[0])

任何数量的空格都可以,但我不知道哪一个是首选的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33147599

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档