“缩进中的制表符和空格使用不一致”

问题:“缩进中的制表符和空格使用不一致”

我试图在Python 3.2中创建一个应用程序,并且一直使用制表符进行缩进,但是即使编辑器也将其中的一些更改为空格,然后在尝试运行时打印出“不一致使用制表符和空格”该程序。

如何将空格更改为制表符?这让我疯狂。(我是编程的初学者)。如果我能在代码中获得一些总体提示,我会很高兴,如果我犯了很多错误,我会很高兴听到。

import random

attraktioner = ["frittfall","bergodalbana","spökhuset"]


class Nojesfalt:
    def __init__(self, attraktion):
        self.val = attraktion
        self.langd = 0
        self.alder = 0


#längdgräns för fritt fall
    def langdgrans(self):
        print("")
        self.langd = int(input("Hur lång är du i cm? "))
        if self.langd < 140:
            print("tyvärr, du är för kort, prova något annat")
            return 0
        elif self.langd >= 140:
            print("håll dig hatten, nu åker vi!")
            print(" ")
            return 1

#åldersgräns för spökhuset
    def aldersgrans(self):
        print("")
        self.alder = int(input("Hur gammal är du? "))
        if self.alder < 10:
            print("tyvärr, du är för ung, prova något annat")
            return 0
        elif self.alder >= 10:
            print("Gå in om du törs!")
            print(" ")
            return 1


#åker attraktion frittfall lr bergodalbana
        def aka(self):
                print("")
        print(self.val)
        tal = random.randint(0,100)
        if tal < 20:
            print("åkturen gick åt skogen, bättre lycka nästa gång")
        elif tal >= 20:
            print("jabbadabbbadoooooooo")
            return 1

#går i spökhuset
        def aka1(self):
                print("")
        print(self.val)
        tal = random.randint(0,100)
        if tal < 20:
            print("du är omringad av spöken och kan inte fortsätta")            return 0
        elif tal >= 20:
            print("Buhuuuuuu, buuuhuuuu")
            return 1

#programkod
print("Välkommen till nöjesfältet, vad vill du göra?")
print(" ")

while 1:
    vald_attr = input("Vad vill du göra?\n1. frittfall\n2. bergodalbana\n3. spökhuset\n4. Avsluta\n")
    if vald_attr == "1":
        val = Nojesfalt(attraktioner[0])
        if val.langdgrans() == 1:
            val.aka()
    elif vald_attr == "2":
        val = Nojesfalt(attraktioner[1])
        val.aka()
    elif vald_attr == "3":
        val = Nojesfalt(attraktioner[2])
        if val.aldersgrans() == 1:
            val.aka1()
    elif vald_attr == "4":
        break

I’m trying to create an application in Python 3.2 and I use tabs all the time for indentation, but even the editor changes some of them into spaces and then print out “inconsistent use of tabs and spaces in indentation” when I try to run the program.

How can I change the spaces into tabs? It’s driving me crazy. (I’m a beginner in programming). I would be glad if I could get some overall tips on my code, if I have done a lot of mistakes I would be happy to hear.

import random

attraktioner = ["frittfall","bergodalbana","spökhuset"]


class Nojesfalt:
    def __init__(self, attraktion):
        self.val = attraktion
        self.langd = 0
        self.alder = 0


#längdgräns för fritt fall
    def langdgrans(self):
        print("")
        self.langd = int(input("Hur lång är du i cm? "))
        if self.langd < 140:
            print("tyvärr, du är för kort, prova något annat")
            return 0
        elif self.langd >= 140:
            print("håll dig hatten, nu åker vi!")
            print(" ")
            return 1

#åldersgräns för spökhuset
    def aldersgrans(self):
        print("")
        self.alder = int(input("Hur gammal är du? "))
        if self.alder < 10:
            print("tyvärr, du är för ung, prova något annat")
            return 0
        elif self.alder >= 10:
            print("Gå in om du törs!")
            print(" ")
            return 1


#åker attraktion frittfall lr bergodalbana
        def aka(self):
                print("")
        print(self.val)
        tal = random.randint(0,100)
        if tal < 20:
            print("åkturen gick åt skogen, bättre lycka nästa gång")
        elif tal >= 20:
            print("jabbadabbbadoooooooo")
            return 1

#går i spökhuset
        def aka1(self):
                print("")
        print(self.val)
        tal = random.randint(0,100)
        if tal < 20:
            print("du är omringad av spöken och kan inte fortsätta")            return 0
        elif tal >= 20:
            print("Buhuuuuuu, buuuhuuuu")
            return 1

#programkod
print("Välkommen till nöjesfältet, vad vill du göra?")
print(" ")

while 1:
    vald_attr = input("Vad vill du göra?\n1. frittfall\n2. bergodalbana\n3. spökhuset\n4. Avsluta\n")
    if vald_attr == "1":
        val = Nojesfalt(attraktioner[0])
        if val.langdgrans() == 1:
            val.aka()
    elif vald_attr == "2":
        val = Nojesfalt(attraktioner[1])
        val.aka()
    elif vald_attr == "3":
        val = Nojesfalt(attraktioner[2])
        if val.aldersgrans() == 1:
            val.aka1()
    elif vald_attr == "4":
        break

回答 0

不要使用标签。

  1. 将您的编辑器设置为使用4个空格进行缩进。
  2. 搜索并替换以4个空格替换所有选项卡。
  3. 确保您的编辑器设置为标签显示为8个空格。

注意:制表符使用8个空格的原因是,您可以立即注意到无意间插入了制表符的情况-例如,在使用制表符而不是空格的示例代码中进行复制和粘贴时。

Don’t use tabs.

  1. Set your editor to use 4 spaces for indentation.
  2. Make a search and replace to replace all tabs with 4 spaces.
  3. Make sure your editor is set to display tabs as 8 spaces.

Note: The reason for 8 spaces for tabs is so that you immediately notice when tabs have been inserted unintentionally – such as when copying and pasting from example code that uses tabs instead of spaces.


回答 1

使用autopep8下面的命令为我修复它:

 autopep8 -i my_file.py

此处链接的文档autopep8

Using the autopep8 command below fixed it for me:

 autopep8 -i my_file.py

Documentation for autopep8 linked here.


回答 2

使用IDLE编辑器,您可以使用以下命令:

  • 菜单编辑全选
  • 菜单格式取消制表区域
  • 假设您的编辑器已用制表符替换了8个空格,请在输入框中输入8。
  • 点击选择,它会修复整个文档。

With the IDLE editor you can use this:

  • Menu EditSelect All
  • Menu FormatUntabify Region
  • Assuming your editor has replaced 8 spaces with a tab, enter 8 into the input box.
  • Hit select, and it fixes the entire document.

回答 3

如果您将Sublime Text用于Python开发,则可以使用Anaconda软件包来避免该错误。安装Anaconda后,在Sublime Text中打开文件,右键单击空白处→选择Anaconda →单击自动格式化。完成。或按Ctrl+ Alt+ R

If you are using Sublime Text for Python development, you can avoid the error by using the package Anaconda. After installing Anaconda, open your file in Sublime Text, right click on the open spaces → choose Anaconda → click on autoformat. Done. Or press Ctrl + Alt + R.


回答 4

通常,人们喜欢缩进空间。各个编辑器之间的一致性更高,从而减少了此类不匹配的情况。但是,您可以缩进制表符。这是你的选择; 但是,您应该注意,每个制表符8个空格的标准有点宽。

关于您的问题,很可能是您的编辑搞砸了。将制表符转换为空格实际上取决于编辑器。

例如,在Emacs上,您可以将方法称为“ untabify”。

在命令行上,您可以使用sed行(将空格数调整为任何您喜欢的值):

   sed -e 's;\t;       ;' < yourFile.py > yourNedFile.py

Generally, people prefer indenting with space. It’s more consistent across editors, resulting in fewer mismatches of this sort. However, you are allowed to indent with tab. It’s your choice; however, you should be aware that the standard of 8 spaces per tab is a bit wide.

Concerning your issue, most probably, your editor messed up. To convert tab to space is really editor-dependent.

On Emacs, for example, you can call the method ‘untabify’.

On command line, you can use a sed line (adapt the number of spaces to whatever pleases you):

   sed -e 's;\t;       ;' < yourFile.py > yourNedFile.py

回答 5

当使用崇高的文本编辑器时,我能够选择inconsistent use of tabs and spaces in indentation出现错误的代码段,然后选择:

view > indentation > convert indentation to spaces

为我解决了这个问题。

When using the sublime text editor, I was able to select the segment of my code that was giving me the inconsistent use of tabs and spaces in indentation error and select:

view > indentation > convert indentation to spaces

which resolved the issue for me.


回答 6

当出现相同错误时我该怎么做:选择所有内容(Str+ A),然后按Shift+ Tab。因此,不再缩进。现在回到您要缩进的行,然后将其放回所需的位置。

它对我有用…

What I did when the same error popped up: Select everything (Str + A) and press Shift + Tab. So nothing was indented anymore. Now go back to the lines you want to have indented, and put it back how you want it.

It worked for me…


回答 7

我最近遇到了同样的问题,发现我只需要将.py文件的字符集转换为UTF-8,这就是Python 3所使用的设置。

顺便说一句,我一直都使用4空格制表符,因此问题并不是由它们引起的。

I recently had the same problem and found out that I just needed to convert the .py file’s charset to UTF-8 as that’s the set Python 3 uses.

BTW, I used 4-space tabs all the time, so the problem wasn’t caused by them.


回答 8

崇高文字3

在崇高的文本,WHILE 编辑一个Python的文件:

Sublime Text菜单 >首选项 >设置-特定于语法

Python.sublime设置

{
    "tab_size": 4,
    "translate_tabs_to_spaces": true
}

Sublime Text 3

In Sublime Text, WHILE editing a Python file:

Sublime Text menu > Preferences > Settings – Syntax Specific :

Python.sublime-settings

{
    "tab_size": 4,
    "translate_tabs_to_spaces": true
}

回答 9

notepad++通过将Tabs 替换为4 Spaces 可以解决此问题:

  1. 选择搜索->查找…或按Ctrl+F
  2. 选择替换标签
  3. 在名为“ 搜索模式”的框中,选择“ 扩展(\ n,\ r,\ t,\ 0,\ x …)
  4. 在字段中查找内容:\ t
  5. 在“ 替换为 ”字段中Space4次。确保此字段中没有其他内容。
  6. 单击按钮全部替换

It is possible to solve this problem using notepad++ by replacing Tabs with 4 Spaces:

  1. Choose Search -> Find… or press Ctrl + F
  2. Select the Replace tab
  3. In the box named Search Mode choose Extended(\n, \r, \t, \0, \x…)
  4. In the field Find what : write \t
  5. In the field Replace with : press Space 4 times. Be sure that there is nothing else in this field.
  6. Click on the button Replace All


回答 10

我有这个问题。解决方案:问题行之前的“制表符”是空格,4、6或8个空格。您应该擦除它们并插入TAB。’\ t’。就这样。

I had this problem. Solution: your ‘tab’ before the problem line is spaces, 4, 6, or 8 spaces. You should erase them and insert TAB. ‘\t’. That’s all.


回答 11

我使用Notepad ++并收到此错误。

在Notepad ++中,您将看到制表符和四个空格都相同,但是当您将代码复制到Python IDLE时您会看到区别,并且带有制表符的行比其他行之前有更多空间。

为了解决该问题,我只是删除了该行之前的选项卡,然后添加了四个空格。

I use Notepad++ and got this error.

In Notepad++ you will see that both the tab and the four spaces are the same, but when you copy your code to Python IDLE you would see the difference and the line with a tab would have more space before it than the others.

To solve the problem, I just deleted the tab before the line then added four spaces.


回答 12

我有同样的错误。我必须在现有的* .py文件中添加几行代码。在记事本++中,它不起作用。

添加代码行并保存后,我得到了相同的错误。当我在PyCharm中打开相同的文件并添加行时,错误消失了。

I had the same error. I had to add several code lines to an existing *.py file. In Notepad++ it did not work.

After adding the code lines and saving, I got the same error. When I opened the same file in PyCharm and added the lines, the error disappeared.


回答 13

我遇到了相同的错误,但无法弄清楚自己在做什么错。

因此,我通过在代码上运行自动缩进并允许机器修复我的错误来修复它。

如果有人想知道我是怎么做到的。简单。进入vim。输入G = gg。

这将自动修复所有问题。祝好运 :)

I got the same errors but could not figure out what I was doing wrong.

So I fixed it by running auto-indent on my code and allowing the machine to fix my fault.

If anyone is wondering how I did that. Simple. Go in vim. Type in G=gg.

This will automatically fix everything. Good luck :)


回答 14

您的问题是由于您的编辑器限制/配置。一些编辑器通过以下方式为您提供解决问题的工具:

  1. 将制表符转换为空格

    例如,如果您使用的是Stani的Python编辑器,则可以对其进行配置以在保存时执行此操作。

  2. 将空格转换为制表符

如果您使用的是ActiveState Komodo,则可以使用一个工具来“制表”代码。正如其他人已经指出的那样,这不是一个好主意。

Eclipse的Pydev提供了“将制表符转换为空格键”和“将制表符转换为空格键”功能。

Your problem is due to your editor limitations/configuration. Some editors provide you of tools to help with the problem by:

  1. Converting tabs into spaces

    For example, if you are using Stani’s Python editor you can configure it to do it on saving.

  2. Converting spaces into tabs

If you are using ActiveState Komodo you have a tool to ‘tabify’ your code. As others already pointed, this is not a good idea.

Eclipse’s Pydev provides functions “Convert tabs to space-tabs” and “Convert space-tabs to tabs”.


回答 15

如果您的编辑器在进行搜索和替换时(例如SciTE)无法识别选项卡,则可以将代码粘贴到Word中,然后使用Ctr-H和^ t搜索,然后找到可以替换为4个空格的选项卡。

If your editor doesn’t recognize tabs when doing a search and replace (like SciTE), you can paste the code into Word and search using Ctr-H and ^t which finds the tabs which then can be replace with 4 spaces.


回答 16

有这个问题从重复这里,但我想我会提供一个视图做现代的编辑和他们所提供的功能繁多。使用python代码时,所有需要在.py文件中使用的东西都需要全部使用Tab键或空格来实现。惯例是使用四个空格进行缩进。大多数编辑器都可以在编辑器上直观地显示代码是使用空格还是制表符缩进,这对于调试非常有帮助。例如,使用atom,转到首选项,然后进入编辑器,您可以看到以下两个选项:

然后,如果您的代码使用空格,则会在代码缩进的地方看到小点:

如果使用选项卡将其缩进,您将看到以下内容:

现在,如果您注意到了,您会发现在使用选项卡时,左侧还有更多错误/警告,这是因为有一个名为pep8 pep8 documentation的东西,该文档基本上是python的统一样式指南,因此所有开发人员都大多将代码编写为相同的标准和外观,在尝试理解其他人的代码时会有所帮助,在pep8中,它倾向于使用空格来缩进而不是使用制表符。我们可以看到编辑器显示有与pep8警告代码有关的警告W191

希望以上所有内容都能帮助您了解所遇到问题的性质以及将来如何解决该问题。

There was a duplicate of this question from here but I thought I would offer a view to do with modern editors and the vast array of features they offer. With python code, anything that needs to be intented in a .py file, needs to either all be intented using the tab key, or by spaces. Convention is to use four spaces for an indentation. Most editors have the ability to visually show on the editor whether the code is being indented with spaces or tabs, which helps greatly for debugging. For example, with atom, going to preferences and then editor you can see the following two options:

Then if your code is using spaces, you will see small dots where your code is indented:

And if it is indented using tabs, you will see something like this:

Now if you noticed, you can see that when using tabs, there are more errors/warnings on the left, this is because of something called pep8 pep8 documentation, which is basically a uniform style guide for python, so that all developers mostly code to the same standard and appearance, which helps when trying to understand other peoples code, it is in pep8 which favors the use of spaces to indent rather than tabs. And we can see the editor showing that there is a warning relating to pep8 warning code W191,

I hope all the above helps you understand the nature of the problem you are having and how to prevent it in the future.


回答 17

有时,tab缩进时会弄乱。一种方法是明显使用tabandbackspace正确缩进代码。

另一种方法是使用space 4次(取决于您要缩进多少)。

这是一种怪异的方式,当我没有其他任何东西起作用时,它对我有用,无论遇到错误的backspaced那一行,我都将该行移到上一行,然后按enter。它会自动将行缩进正确的位置,此后我没有收到任何错误。

希望这会有所帮助。

Sometimes, tab does mess up while indenting. One way is to obviously use the tab and backspace to correctly indent the code.

Another way is to use space 4 times (depending on how much you want to indent).

A weird way that worked for me when nothing else worked, whichever line I getting the error, I backspaced that line to the previous line and then pressed enter. It automatically indented the line to correct position and I was not getting any error after that.

Hopefully, this should help.


回答 18

我有同样的问题,并使用以下python脚本进行修复。希望对别人有帮助。

这是因为使用制表符和空格来缩进代码。在此脚本中,我将每个选项卡替换为四个空格。

input_file = "source code path here"  # e.g. source.py
output_file = "out put file path here"  # e.g out.py
with open(input_file, 'r') as source:
    with open(output_file, 'a+') as result:
        for line in source:
            line = line.replace('\t', '    ')
            result.write(line)

如果您使用sublime或其他任何提供文本替换工具的编辑器,则可以用编辑器中的四个空格替换所有制表符。

I had the same problem and fix it using following python script. hope it help others.

it is because of using tabs and spaces for indenting code. in this script I replace each tab with four spaces.

input_file = "source code path here"  # e.g. source.py
output_file = "out put file path here"  # e.g out.py
with open(input_file, 'r') as source:
    with open(output_file, 'a+') as result:
        for line in source:
            line = line.replace('\t', '    ')
            result.write(line)

if you use sublime or any other editor which gives you the tool to replace text you can replace all tabs by four spaces from editor.


回答 19

对于python使用Idle,对于python3使用Idle3。

Use, Idle for python, or Idle3 for python3.


回答 20

使用Vim编辑器解决这个问题

  1. 打开终端(Ctrl+ Alt+ T)。
  2. 转到文件所在的目录(cd <path_to_your_directory>)。例如:cd /home/vineeshvs/work
  3. 在Vim(vim <file_name>)中打开文件。例如:vim myfile.txt
  4. [可选步骤]在Vim中启用搜索关键字突出显示(ESC :set hlsearch
  5. 转到存在此问题的行(ESC :<line_number>)。例::53ESC一次按钮后,在Vim编辑器中。
  6. 在Vim(:.,$s/\t/<give_as_many_spaces_as_you_want_to_replace_tab>/gc)中使用所需的空格数替换标签。例如:使用以下命令将Tab替换为四个空格::.,$s/\t/ /gcESC 一次按钮后)。此过程是交互式的。您可以y使用空格替换选项卡,并n跳过特定的替换。按ESC当你与所需要的替代完成。

Solving this using Vim editor

  1. Open terminal (Ctrl + Alt + T).
  2. Go to the directory where the file is located (cd <path_to_your_directory>). Ex: cd /home/vineeshvs/work.
  3. Open the file in Vim (vim <file_name>). Ex: vim myfile.txt .
  4. [Optional step] Enable search keyword highlighting in Vim (ESC :set hlsearch)
  5. Go to the line where you have this problem (ESC :<line_number>). Ex: :53 in Vim editor after pressing ESC button once.
  6. Replace tabs using the required number of spaces in Vim (:.,$s/\t/<give_as_many_spaces_as_you_want_to_replace_tab>/gc). Ex: Tab will be replaced with four spaces using the following command: :.,$s/\t/ /gc after pressing ESC button once). This process is interactive. You may give y to replace the tab with spaces and n to skip a particular replacement. Press ESC when you are done with the required replacements.

回答 21

我的一个.py文件奇怪地遇到了类似的问题。我只是在Pycharm中打开了文件,然后按Option+ Command+ L一次正确地格式化了文件内容。

我怀疑自己遇到了麻烦,因为我是通过jupyter实验室对这个特定的.py文件进行编码的,而不是我通常选择的sublime文本或Pycharm,因此遇到了一些隐藏的缩进问题,这里提到了许多答案

I oddly ran into a similar issue with one of my .py files. I simply opened the file in Pycharm and pressed Option+Command+L which correctly formats the file contents in one go.

I suspect I was having trouble because I coded this particular .py file through jupyter labs as opposed to my usual choice of sublime text or Pycharm and therefore ran into some hidden indentation issues many answers here have alluded to


回答 22

好吧,我遇到了同样的问题,我意识到问题是我将代码从另一个python编辑器复制到了sublime。

我在使用jupyter笔记本工作,然后将代码复制到了高级代码中。显然,当您进行特定的修改(例如在函数中移动代码)时,缩进变得混乱,这就是问题所在。

因此,只需坚持一位编辑。如果这样做,那么您将没有问题。

Well I had the same problem and I realised that the problem is that I copied code from another python editor to sublime.

I was working with jupyter notebook and then I copied the code into sublime. Apparently when you make specific modifications (like moving code in functions) then indentation gets messy and this is where the problem comes from.

So just stick to one editor. If you do so, then you will be having no problem.


回答 23

使用pylint它会为您提供有关需要多少空间以及在何处的详细报告。

Use pylint it will give you a detailed report about how many spaces you need and where.


回答 24

如果您使用ATOM:

转到菜单:程序包->空白->将所有制符转换为空格

If you use ATOM:

Go to Menu: Packages –> WhiteSpace –> Convert all Tabs to Spaces


回答 25

尝试删除缩进,然后系统地按Tab键或空格键4次。当我使用Tab键缩进然后在下一行使用空格键时,通常会发生这种情况。

Try deleting the indents and then systematically either pressing tab or pressing space 4 times. This usually happens to me when I have an indent using the tab key and then use the space key in the next line.


回答 26

突出显示缩进的位,然后单击制表符。然后它们将变得一致:)

Highligt the indented bits, and then click tabs. They will then become consistent :)