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

41 投票
4 回答
74960 浏览
提问于 2025-04-17 06:52

我正在使用Python的cog模块来生成C++的基础代码,目前效果很好。不过我有一个担心,就是生成的代码本身就很丑,而且没有缩进,这让它看起来更糟。我懒得在字符串生成函数里调整缩进,所以我想知道有没有Python的工具函数可以用来给多行字符串加缩进?

4 个回答

12

如果你有一个开头的换行符:

Heredoc可以包含一个字面上的换行符,或者你可以在前面加一个换行符。

indent = '    '

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

这里用pprint展示了一下:

>>> pprint(indented)

' Hello\n World\n '

虽然看起来有点别扭,但确实可以用


如果你没有开头的换行符:

indent = '    '

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

这是可选的,可以去掉第一个换行符和末尾的空格或制表符

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

你可以通过在字符串的每一行前面加上适当数量的空白字符来实现缩进。这可以很简单地通过使用在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
2

为什么不通过命令行的代码格式化工具,比如astyle,来处理输出呢?

撰写回答