4 spaces for Indentation - Syntax error

倾然丶 夕夏残阳落幕 提交于 2019-12-11 05:56:05

问题


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

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


回答1:


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.

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.

Hope this helps




回答2:


Throwing an exception: pass solves it. It is not needed when using indentation from a Text editor. That's weird.



来源:https://stackoverflow.com/questions/39070917/4-spaces-for-indentation-syntax-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!