如何修复Python缩进

2024-03-29 06:27:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些Python代码的缩进不一致。有很多制表符和空格的混合使得事情变得更糟,甚至空格缩进也不被保留。

代码按预期工作,但很难维护。

如何在不破坏代码的情况下修复缩进(比如HTML Tidy,但对于Python)?


Tags: 代码html情况事情制表符tidy空格更糟
3条回答

我会伸手让autopep8来做这个:

$ # see what changes it would make
$ autopep8 path/to/file.py --select=E101,E121 --diff

$ # make these changes
$ autopep8 path/to/file.py --select=E101,E121 --in-place

注意:E101 and E121是pep8缩进(我认为您可以简单地通过--select=E1来解决所有与缩进相关的问题-那些从E1开始的问题)。

可以使用递归标志将此应用于整个项目:

$ autopep8 package_dir --recursive --select=E101,E121 --in-place

另请参见Tool to convert Python code to be PEP8 compliant

如果您使用的是Vim,请参见^{}

                                                        *:ret* *:retab*
:[range]ret[ab][!] [new_tabstop]
                        Replace all sequences of white-space containing a
                        <Tab> with new strings of white-space using the new
                        tabstop value given.  If you do not specify a new
                        tabstop size or it is zero, Vim uses the current value
                        of 'tabstop'.
                        The current value of 'tabstop' is always used to
                        compute the width of existing tabs.
                        With !, Vim also replaces strings of only normal
                        spaces with tabs where appropriate.
                        With 'expandtab' on, Vim replaces all tabs with the
                        appropriate number of spaces.
                        This command sets 'tabstop' to the new value given,
                        and if performed on the whole file, which is default,
                        should not make any visible change.
                        Careful: This command modifies any <Tab> characters
                        inside of strings in a C program.  Use "\t" to avoid
                        this (that's a good habit anyway).
                        ":retab!" may also change a sequence of spaces by
                        <Tab> characters, which can mess up a printf().
                        {not in Vi}
                        Not available when |+ex_extra| feature was disabled at
                        compile time.

例如,如果您只是键入

:ret

所有标签页都将展开到空格中。

你可能想

:se et  " shorthand for :set expandtab

以确保任何新行都不会使用文字制表符。


如果你不使用Vim

perl -i.bak -pe "s/\t/' 'x(8-pos()%8)/eg" file.py

将用空格替换制表符,假设制表符每8个字符停止一次,在file.py中(为了以防万一,原始制表符将转到file.py.bak)。如果您的止动块是每4个空格,则将8s替换为4s。

使用在Python安装的Tools/scripts/目录中找到的reindent.py脚本:

Change Python (.py) files to use 4-space indents and no hard tab characters. Also trim excess spaces and tabs from ends of lines, and remove empty lines at the end of files. Also ensure the last line ends with a newline.

请查看该脚本以获取详细的使用说明。

相关问题 更多 >