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

标签 python string indentation

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

最佳答案

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

结果:

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

关于python - 如何缩进多行字符串的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8234274/

相关文章:

javascript - 如何进行多个正则表达式替换

python - 如何在 Python 中使用 pprint 进行缩进?

c++ - 如何让 emacs 像对待 '{' 和 '}' 一样对待#ifdef 和#endif?

python - 正则表达式转义字符串的一部分

python - 为什么 getoldtweets3 库提供 404 错误?

python - SWIG 结构指针作为输出参数

python - 用于替换不在引号之间的特定单词的正则表达式

python - 尝试一次通过搜索发送一个列表项

java - 如何循环回到字符串的开头? super 技能,加密-解密

c++ - 在 Xcode 上打开用 emacs 编写的代码出现严重缩进