将Python 2语法移植到Python 3

0 投票
1 回答
4715 浏览
提问于 2025-04-17 04:22

我正在尝试在python3中运行以下代码,但我很确定这段代码是为python2写的:

f = open(filename, 'r')
self.lines = f.readlines()
f.close()
if self.lines[-1] != "\n" :
    self.lines.append("\n")

但是我遇到了以下错误:

  File "randline.py", line 32
    if self.lines[-1] != "\n" :
                              ^
TabError: inconsistent use of tabs and spaces in indentation

你能帮我找出正确的写法吗?

1 个回答

6

Python 2允许你在代码缩进时混用空格和制表符(Tab),所以你可以像这样缩进:

def foo():
[this is a tab it counts like eight spaces             ]for each in range(5):
[this is a tab it counts like eight spaces             ][space][space]print(each)
[space][space][space][space][space][space][space][space]print("Done!")

在Python 2中,第2行和第4行的缩进级别是一样的,但第2行是用制表符缩进的,而第4行是用空格缩进的。打印到控制台上,它看起来是这样的:

def foo()
        for each in range(5):
          print(5)
        print("Done!")

不过大多数代码编辑器都允许你设置一个制表符等于多少个空格。如果你把它设置为四个空格,那么你会看到:

def foo()
    for each in range(5):
      print(5)
        print("Done!")

缩进还是一样的,但现在看起来缩进是错的

因此,Python 3不允许在同一缩进级别(也就是第2行和第4行)使用不同的缩进方式。你仍然可以混用制表符和空格,但不能在同一缩进级别中混用。这意味着

def foo():
[this is a tab it counts like eight spaces             ]for each in range(5):
[this is a tab it counts like eight spaces             ][space][space]print(each)
[this is a tab it counts like eight spaces             ]print("Done!")

这样是可以的,

def foo():
[this is a tab it counts like eight spaces             ]for each in range(5):
[space][space][space][space][space][space][space][space][space][space]print(each)
[this is a tab it counts like eight spaces             ]print("Done!")

这样也是可以的。

唯一让缩进看起来奇怪的方式是,如果你把一个制表符设置为超过八个空格,那么缩进不仅看起来明显不对,你会发现一个制表符会缩进12个空格(在下面的例子中),这样你就会意识到你插入的是一个制表符,而不是四个空格。

def foo():
            for each in range(5):
          print(each)
            print("Done!")

当然,解决你所有问题的方法就是像评论中所说的,永远不要使用制表符。我不明白为什么Python 3还允许使用制表符,真的没有什么好理由。

撰写回答