python 将python缩进从空格转换为制表符的工具?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/338767/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Tool to convert python indentation from spaces to tabs?
提问by Corey
I have a some .py files that use spaces for indentation, and I'd like to convert them to tabs.
我有一些使用空格进行缩进的 .py 文件,我想将它们转换为制表符。
I could easily hack together something using regexes, but I can think of several edge cases where this approach could fail. Is there a tool that does this by parsing the file and determining the indentation level the same way the python interpreter does?
我可以使用正则表达式轻松地将某些东西组合在一起,但我可以想到这种方法可能会失败的几种边缘情况。是否有一种工具可以通过解析文件并以与 python 解释器相同的方式确定缩进级别来执行此操作?
回答by wimh
If there are not many files to convert, you can open them in vim, and use the :retab
command.
如果要转换的文件不多,可以在vim 中打开,使用:retab
命令。
See the vim documentationfor more information.
有关更多信息,请参阅vim 文档。
回答by Greg
Python includes a script for the opposite (tabs to spaces). It's C:\Python24\Tools\Scripts\reindent.py
for me
Python 包含一个相反的脚本(制表符到空格)。这是C:\Python24\Tools\Scripts\reindent.py
给我的
回答by Orjanp
:retab will swap tab with spaces, and :retab! will swap spaces with tab. 1 tab = 4 spaces, 4 spaces = 1 tab, depending on your tab setting.
:retab 将用空格交换制表符,而 :retab! 将与制表符交换空格。1 个制表符 = 4 个空格,4 个空格 = 1 个制表符,具体取决于您的制表符设置。
回答by mzuther
回答by Alastair
In emacs, M-x tabify
will convert spaces to tabs where possible. You'll probably want to set the tab-width
variable appropriately.
在 emacs 中,M-x tabify
将尽可能将空格转换为制表符。您可能希望tab-width
适当地设置变量。
I don't know if this addresses your concern that spaces be interpreted in the same way as the python interpreter, but you could always load up python-mode and use M-x indent-region
.
我不知道这是否解决了您对空格的解释方式与 python 解释器相同的担忧,但您始终可以加载 python-mode 并使用M-x indent-region
.