繁体   English   中英

如何缩进多行字符串的内容?

[英]How to indent the contents of a multi-line string?

我正在使用 python cog模块来生成 C++ 样板代码,到目前为止它运行良好,但我唯一担心的是生成的代码本身很丑,因为它没有缩进而变得更糟。 我懒得在字符串生成函数中正确缩进,所以我想知道是否有一个 Python util 函数来缩进多行字符串的内容?

您可以通过用适当数量的填充字符填充每一行来缩进字符串中的行。 这可以通过使用在 Python 3.3 中添加到模块中的textwrap.indent()函数轻松完成。 或者,您可以使用下面的代码,该代码也适用于早期的 Python 版本。

try:
    import textwrap
    textwrap.indent
except AttributeError:  # undefined function (wasn't added until Python 3.3)
    def indent(text, amount, ch=' '):
        padding = amount * ch
        return ''.join(padding+line for line in text.splitlines(True))
else:
    def indent(text, amount, ch=' '):
        return textwrap.indent(text, amount * ch)

text = '''\
And the Lord God said unto the serpent,
Because thou hast done this, thou art
cursed above all cattle, and above every
beast of the field; upon thy belly shalt
thou go, and dust shalt thou eat all the
days of thy life: And I will put enmity
between thee and the woman, and between
thy seed and her seed; it shall bruise
thy head, and thou shalt bruise his
heel.

3:15-King James
'''

print('Text indented 4 spaces:\n')
print(indent(text, 4))

结果:

Text indented 4 spaces:

    And the Lord God said unto the serpent,
    Because thou hast done this, thou art
    cursed above all cattle, and above every
    beast of the field; upon thy belly shalt
    thou go, and dust shalt thou eat all the
    days of thy life: And I will put enmity
    between thee and the woman, and between
    thy seed and her seed; it shall bruise
    thy head, and thou shalt bruise his
    heel.

    3:15-King James

如果你有一个领先的换行符:

Heredocs 可以包含一个文字换行符,或者您可以预先添加一个。

indent = '    '

indent_me = '''
Hello
World
''' 
indented = indent_me.replace('\n', '\n' + indent)
print(indented)

这是它在 pprint 转储中显示的:

>>> pprint(缩进)

' Hello\\n World\\n '

尴尬,但有效


如果您没有前导换行符:

indent = '    '

indent_me = '''\
Hello
World
''' 
indented = indent + indent_me.replace('\n', '\n' + indent)
print(indented)

可选,修剪第一个换行符和尾随空格/制表符

.lstrip('\n').rstrip(' \t')

为什么不通过命令行代码格式化程序(例如 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM