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 3.3中添加到模块的^{} 函数轻松完成。或者,您可以使用下面的代码,这些代码也适用于早期的Python版本。
结果:
如果你有一个领先的新闻热线:
Heredocs可以包含文本换行符,也可以在换行符前加上前缀。
这是pprint dump中显示的:
很尴尬,但很管用
如果没有领先的换行符:
可选,修剪第一个换行符和尾随空格/制表符
为什么不通过命令行代码格式化程序(如astyle)传递输出呢?
相关问题 更多 >
编程相关推荐