缩进4个空格-语法错误 [英] 4 spaces for Indentation - Syntax error

查看:74
本文介绍了缩进4个空格-语法错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用4个空格进行缩进,但出现语法错误.当我在文本编辑器中使用缩进时,效果很好.文本编辑器仅创建1个块,我无法对其进行编辑.空格不能用作缩进吗?

I'm using 4 spaces for indentation, but get a Syntax error. When I use the indentation in the Text editor, works fine. The text editor creates just 1 block, that I'm unable to edit it. Are spaces not able to be used as indentation?

def replace_line(file_name, line_num, text):
    try:
            lines = open(file_name, 'r').readlines()
            lines[line_num] = text
            out = open(file_name, 'w')
            out.writelines(lines)
            out.close()
        if not var and not var2:
            return

在if not var行上出现语法错误.

I get the syntax error on the if not var line.

推荐答案

如果由于缩进而出现语法错误,则很可能与您的代码同时包含 TABS SPACES 作为缩进方法.即使代码似乎从左开始缩进相同的数量,但 TAB 是单个符号,而使用 SPACE 的相同缩进则为4(在您的大小写)符号. Python吓坏了并抛出错误,因为它看不到所见代码的呈现,并且在行之前使用的符号数量不一致.

If you're getting Syntax Error because of indentations it is most probably related to the fact that your code includes both TABS and SPACES as methods of indentation. Even though the code might appear to be be indented the same amount from the left, a TAB is a single symbol, whereas the same indentation using SPACEs takes 4 (in your case) symbols. Python freaks out and throws an error, because it doesn't see the rendering of code you see, it sees an inconsistent number of symbols used before the line.

要解决此问题,请首先在 all 选项卡中使用适当的空格代替,然后遍历代码,并确保代码中的所有缩进均正确无误.如果您使用的是Sublime Text之类的编辑器,则只需单击一下即可完成,而更原始的编辑器会发现 TAB / SPACE 的区别可能更大乏味.

To fix this, firstly substitute all tabs with the appropriate equivalent of spaces, and then go through your code and make sure that all the indentation in your code is valid and correct. If you're using an editor like Sublime Text then you can do this with one or two clicks, with a more primitive editor finding the TAB/SPACE difference might be much more tedious.

希望这会有所帮助

这篇关于缩进4个空格-语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆