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

2024-05-15 11:02:45 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: 模块函数字符串代码内容util样板cog
3条回答

只需在每个行中填充适当数量的填充字符,就可以缩进字符串中的行。这可以通过使用在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))

结果:

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 dump中显示的:

>>> 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')

为什么不通过命令行代码格式化程序(如astyle)传递输出呢?

相关问题 更多 >