Spaces are not treated as equivalent to tab. A line indented with a tab is at a different indentation from a line indented with 1, 2, 4 or 8 spaces.
反例证明(错误,或者充其量是有限的 - tab != 4 个空格):
x = 1
if x == 1:
^Iprint "fff\n"
print "yyy\n"
The '^I
' shows a TAB. When run through Python 2.5, I get the error:
File "xx.py", line 4
print "yyy\n"
^
IndentationError: unindent does not match any outer indentation level
由此可见,在 Python 2.5 中,制表符不等于空格(特别是不等于 4 个空格)。
哎呀——尴尬;我的反例证明表明制表符不等于 4 个空格。作为亚历克斯·马泰利指出在一个comment,在Python 2中,制表符相当于8个空格,并且用一个制表符和8个空格调整示例表明情况确实如此。
x = 1
if x != 1:
^Iprint "x is not 1\n"
print "y is unset\n"
在 Python 2 中,这段代码可以工作,不打印任何内容。
在 Python 3 中,规则略有不同(如noted by 安蒂·哈帕拉)。比较:
- Python 2 关于缩进
- Python 3 关于缩进
Python 2 说:
首先,制表符被替换为一到八个空格(从左到右),使得直到并包括替换的字符总数是八的倍数(这与 Unix 使用的规则相同)。第一个非空白字符之前的空格总数决定了该行的缩进。不能使用反斜杠将缩进分割为多个物理行;第一个反斜杠之前的空格决定了缩进。
Python 3 说:
制表符被(从左到右)替换为一到八个空格,使得直到(包括替换)的字符总数是八的倍数(这与 Unix 使用的规则相同)。第一个非空白字符之前的空格总数决定了该行的缩进。不能使用反斜杠将缩进分割为多个物理行;第一个反斜杠之前的空格决定了缩进。
(除了开头词“第一”之外,这些都是相同的。)
Python 3 添加了一个额外的段落:
如果源文件混合制表符和空格,使得含义依赖于空格中制表符的价值,则缩进将被拒绝为不一致;在这种情况下会引发 TabError 。
This means that the TAB vs 8-space example that worked in Python 2 would generate a TabError in Python 3. It is best — necessary in Python 3 — to ensure that the sequence of characters making up the indentation on each line in a block is identical. PEP8 says 'use 4 spaces per indentation level'. (Google's coding standards say 'use 2 spaces'.)