gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 20:52:27 25 4
gpt4 key购买 nike

我正在使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com