如何缩进多行字符串的内容?
我正在使用 python cog 模块生成 C++ 样板代码,到目前为止效果很好,但是我唯一担心的是生成的代码本身就很难看,而且由于它没有缩进,所以变得更糟。我懒得在字符串生成函数中得到正确的缩进,所以我想知道是否有一个Python util函数来缩进多行字符串的内容?
I'm using the python cog module to generate C++ boilerplate code, and it is working great so far, but my only concern is that the resulting code, which is ugly by itself, is made worse by the fact that it's not indented. I'm too lazy to get the indentation right in the string generation function, so I'm wondering if there is a Python util function to indent the content of a multi-line string?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您只需用适当数量的填充字符填充每一行即可缩进字符串中的行。这可以通过使用
textwrap.indent()< 轻松完成/code>
函数是在 Python 3.3 中添加到模块中的。或者,您可以使用下面的代码,该代码也适用于早期的 Python 版本。
结果:
You can indent the lines in a string by just padding each one with proper number of pad characters. This can easily be done by using the
textwrap.indent()
function which was added to the module in Python 3.3. Alternatively you could use the code below which will also work in earlier Python versions.Result:
如果您有一个前导换行符:
Heredocs 可以包含一个文字换行符,或者您可以在前面添加一个换行符。
这是 pprint 转储中显示的:
笨拙,但有效
如果您没有前导换行符:
可选,修剪第一个换行符和尾随空格/制表符
If you have a leading newline:
Heredocs can contain a literal newline, or you can prepend one.
Here is it shown in pprint dump:
Awkward, but works
If you do not have a leading newline:
Optional, trim first newline and trailing spaces/tabs
为什么不通过命令行代码格式化程序(例如 astyle)管道输出?
Why not pipe the output through a command-line code formatter such as astyle?
python
Tools/Scripts/
目录中有一个脚本,主要用于修复整个 python 文件的缩进。但是,您可以轻松地稍微调整脚本并将其应用于代码段/行或其他类型的文件。该脚本也可以在线找到,此处:
http://svn.python.org/projects/python/trunk /Tools/scripts/reindent.py
或者,作为此处的模块:
http://pypi.python.org/pypi/Reindent/0.1.0
There is a script located in the python
Tools/Scripts/
directory which is primarily for fixing the indentation of entire python files. However, you can easily tweak the script a little and apply it to sections/lines of code, or other types of files.The script is also located online, here:
http://svn.python.org/projects/python/trunk/Tools/scripts/reindent.py
Or, as a module here:
http://pypi.python.org/pypi/Reindent/0.1.0