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

lur*_*her 21 python string

我正在使用python cog模块生成C++样板代码,到目前为止它工作得很好,但我唯一担心的是,由于它没有缩进,因此产生的代码本身很难看.我太懒了,不能在字符串生成函数中得到缩进,所以我想知道是否有一个Python util函数来缩进多行字符串的内容?

mar*_*eau 25

您可以通过用适当数量的填充字符填充每个字符串来缩进字符串中的行.这可以通过使用textwrap.indent()Python 3.3中添加到模块的函数轻松完成.或者,您可以使用下面的代码,该代码也适用于早期的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))
Run Code Online (Sandbox Code Playgroud)

结果:

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
Run Code Online (Sandbox Code Playgroud)

  • 从 python v3.3 开始,你可以只 `import textwrap` 然后 `textwrap.indent(text, ' ' * 4)` (4认同)

Tho*_*ner 6

如果您有领先的换行符:

Heredocs可以包含文字换行符,也可以添加一个换行符。

indent = '    '

indent_me = '''
Hello
World
''' 
indented = indent_me.replace('\n', '\n' + indent)
print(indented)
Run Code Online (Sandbox Code Playgroud)

这是pprint转储中显示的内容:

>>> pprint(缩进)

' Hello\n World\n '

尴尬,但可行


如果您没有领先的换行符:

indent = '    '

indent_me = '''\
Hello
World
''' 
indented = indent + indent_me.replace('\n', '\n' + indent)
print(indented)
Run Code Online (Sandbox Code Playgroud)

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

.lstrip('\n').rstrip(' \t')
Run Code Online (Sandbox Code Playgroud)


小智 2

为什么不通过命令行代码格式化程序(例如 astyle)管道输出?