【问题标题】:Unindent does not match any outer indentation level? [duplicate]Unndent 不匹配任何外部缩进级别? [复制]
【发布时间】:2012-07-04 21:33:36
【问题描述】:

可能重复:
IndentationError: unindent does not match any outer indentation level

我有以下 python 代码。

import sys

ins = open( sys.argv[1], "r" )
array = []
for line in ins:
    s = line.split()
    array.append( s[0] ) # <-- Error here 
print array

ins.close()

python解释器报错

  File "sort.py", line 7
    array.append( s[0] )
                       ^
IndentationError: unindent does not match any outer indentation level

为什么会这样?以及如何纠正这个错误?

【问题讨论】:

  • PEP-8 建议不要写像foo( x, y ) 这样的函数参数。
  • python -tt运行你的脚本

标签: python


【解决方案1】:

您正在混合制表符和空格(有时会发生 :)。使用其中一种。

我查看了您的来源:

    s = line.split()  # there's a tab at the start of the line
    array.append( s[0] )  # spaces at the start of the line

旁白:作为一个友好的建议,考虑使用with 打开您的文件。这样做的好处是当你完成或遇到异常时,文件会自动为你关闭(不需要close())。

array = []
with open( sys.argv[1], "r" ) as ins:  # "r" really not needed, it's the default.
   for line in ins:
      s = line.split()
      # etc...

【讨论】:

    【解决方案2】:

    使用python -tt sort.py 运行您的代码。

    它会告诉你是否混合了制表符和空格。

    【讨论】:

      【解决方案3】:

      使用空格或制表符确保您的缩进是一致的,而不是两者的混合。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-06-28
        • 1970-01-01
        • 2018-02-08
        • 1970-01-01
        • 2020-08-14
        • 2018-02-16
        • 2013-09-04
        • 2010-10-04
        相关资源
        最近更新 更多