python的空白问题

use*_*854 4 python whitespace komodo

我目前在Windows 7中使用Komodo Edit,但是,我在使用TextWrangler的Mac上遇到过这个问题.无论出于何种原因,当我用Python编写时,我遇到了一些空白错误,这是一个很大的问题.例如,一切看起来都是正确的标签,但Komodo目前给我一个"模糊的空白"错误

//How it appears in my editor
def SaveList(self, directory):
    templist = []
    templistbox2 = []
    for n,i in enumerate(self.listbox2.get(0,END)): 
       templistbox2.insert(n, re.sub(r'^[0-9]*[.]',"",str(i)))
    for filename in sorted(os.listdir(directory)):
        self.templist.insert(i, filename)
        print filename #whitespace error here
Run Code Online (Sandbox Code Playgroud)

考虑到我在Windows和Mac上都经历过两个不同的编辑器,我想知道是否有一些我不知道的设置,或者我是否做错了什么.

unu*_*tbu 7

当我将代码复制到文件test.py并运行时

cat -A test.py
Run Code Online (Sandbox Code Playgroud)

我知道了

//How it appears in my editor$
def SaveList(self, directory):$
    templist = []$
    templistbox2 = []$
    for n,i in enumerate(self.listbox2.get(0,END)): $
       templistbox2.insert(n, re.sub(r'^[0-9]*[.]',"",str(i)))$
    for filename in sorted(os.listdir(directory)):$
        self.templist.insert(i, filename)$
^I    print filename #whitespace error here$
Run Code Online (Sandbox Code Playgroud)

这表示^I在最后一行有一个制表符(由...表示)后跟四个空格.

我不确定Windows上的等效工具是什么,但Mac应该有cat -A命令.它将显示选项卡与空格的位置.


有一个名为reindent.py的程序,它会将标签转换为空格:

reindent.py test.py
Run Code Online (Sandbox Code Playgroud)

在Unix上还有一个unexpand命令,它将空格转换为制表符.


大多数Python程序员使用空格而不是制表符来缩进.您在Web上找到的大多数Python代码都使用空格而不是制表符.

您的编辑器可能正在添加选项卡,但如果您从Web获取了一小段代码,则您的文件现在可能包含选项卡和空格.

最简单的方法是采用流程并采用空格缩进惯例,因此您不必重新格式化其他人的代码.

顺便说一下,采用空格缩进惯例并不意味着SPACE每个缩进级别必须按4次.您的编辑器应该有一个配置选项,可以按下TAB插入4个空格.