gpt4 book ai didi

Python对缩进制表符和空格的解释

转载 作者:IT老高 更新时间:2023-10-28 21:56:33 24 4
gpt4 key购买 nike

我决定学习一点 Python。第一个介绍说它使用缩进来分组语句。虽然最好的习惯显然是只使用其中一种,但如果我互换它们会发生什么?多少个空格将被视为等于一个制表符?或者如果混合使用制表符和空格,它会完全不起作用吗?

最佳答案

空格不被视为等同于制表符。以制表符缩进的行与以 1、2、4 个 或 8 个空格缩进的行的缩进不同。

通过反例证明(错误,或者,充其量是有限的 - 制表符!= 4 个空格):

x = 1
if x == 1:
^Iprint "fff\n"
print "yyy\n"

'^I' 显示一个 TAB。通过 Python 2.5 运行时,出现错误:

  File "xx.py", line 4
print "yyy\n"
^
IndentationError: unindent does not match any outer indentation level

由此表明在 Python 2.5 中,制表符不等于空格(尤其是不等于 4 个空格)。


哎呀 - 尴尬;我的反例证明表明制表符不等于 4 个空格。如Alex Martellicomment 中指出,在 Python 2 中,制表符相当于 8 个空格,将示例改编为制表符和 8 个空格表明确实如此。

x = 1
if x != 1:
^Iprint "x is not 1\n"
print "y is unset\n"

在 Python 2 中,此代码有效,不打印任何内容。


在 Python 3 中,规则略有不同(如 notedAntti Haapala )。比较:

Python 2 说:

First, tabs are replaced (from left to right) by one to eight spaces such that the total number of characters up to and including the replacement is a multiple of eight (this is intended to be the same rule as used by Unix). The total number of spaces preceding the first non-blank character then determines the line’s indentation. Indentation cannot be split over multiple physical lines using backslashes; the whitespace up to the first backslash determines the indentation.

Python 3 说:

Tabs are replaced (from left to right) by one to eight spaces such that the total number of characters up to and including the replacement is a multiple of eight (this is intended to be the same rule as used by Unix). The total number of spaces preceding the first non-blank character then determines the line’s indentation. Indentation cannot be split over multiple physical lines using backslashes; the whitespace up to the first backslash determines the indentation.

(除了开头的单词“First”之外,它们是相同的。)

Python 3 增加了一个额外的段落:

Indentation is rejected as inconsistent if a source file mixes tabs and spaces in a way that makes the meaning dependent on the worth of a tab in spaces; a TabError is raised in that case.

这意味着在 Python 2 中运行的 TAB 与 8-space 示例将在 Python 3 中生成 TabError。最好(在 Python 3 中是必需的)确保字符序列 block 中每一行的缩进是相同的。 PEP8说“每个缩进级别使用 4 个空格”。 (Google 的编码标准说“使用 2 个空格”。)

关于Python对缩进制表符和空格的解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2034517/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com