TabError: inconsistent use of tabs and spaces in indentation

TabError: inconsistent use of tabs and spaces in indentation

这个错误,很简单,意思就是tab和空格混用了。

在python代码中,一般要么都用空格来表示缩进,要么都用tab来表示缩进。

那如果出现这样的问题,如何去排查代码中的空格和tab呢?

  • 运行时报错

TabError: inconsistent use of tabs and spaces in indentation

  • 找错误文件位置

提示了以上错误,并且说明是在哪个文件哪一行出现的问题,那这样就很简单了,找到这个文件,用一个文本编辑器打开这个文件,最好不要用windows自带的文本编辑器,我是用Notepa++打开的,找到错误的那一行,如下:

TabError: inconsistent use of tabs and spaces in indentation

找到错误位置后,仔细看看和其他代码没啥不一样啊,因为在这里空格键和tab显示出来的结果都是“空白”,啥也没有。

  • 显示tab和空格键

有什么方法可以让我们看到空格键和tab的区别?我自己想到了一种,比较简单。

  1. 将错误文本附近的几行代码复制出来
  2. 在电脑上新建一个word文档(我的电脑是windows,mac好像也可以有word,或者WPS)
  3. 将刚才复制的代码粘贴到文档中,如下:

TabError: inconsistent use of tabs and spaces in indentation

咋一看也没啥区别,这里需要设置word的显示,有图为证:

  1. TabError: inconsistent use of tabs and spaces in indentation
  2. TabError: inconsistent use of tabs and spaces in indentation
  3. TabError: inconsistent use of tabs and spaces in indentation
  4. 看到那两个选项没,勾选即可,现在再来看看

TabError: inconsistent use of tabs and spaces in indentation

这下有区别了吧,报错的那一行用的是tab缩进,而其他行用的是空格缩进,一目了然,这和标题一致了,如何改,应该就不用多说了吧。

谢谢!