我正在使用python cog模块生成C ++样板代码,到目前为止它工作得很好,但我唯一关心的是,由此产生的代码本身很难看,事实上,它没有缩进。我懒得在字符串生成函数中得到缩进,所以我想知道是否有Python util函数来缩进多行字符串的内容?
答案 0 :(得分:23)
您可以通过用适当数量的填充字符填充每个字符串来缩进字符串中的行。这可以通过使用添加到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
答案 1 :(得分:4)
Heredocs可以包含文字换行符,也可以包含一个。
indent = ' '
indent_me = '''
Hello
World
'''
indented = indent_me.replace('\n', '\n' + indent)
print(indented)
这是在pprint dump中显示的:
>>> pprint(缩进)
' Hello\n World\n '
尴尬,但有效
indent = ' '
indent_me = '''\
Hello
World
'''
indented = indent + indent_me.replace('\n', '\n' + indent)
print(indented)
可选,修剪第一个换行符和尾随空格/制表符
.lstrip('\n').rstrip(' \t')
答案 2 :(得分:3)
为什么不通过命令行代码格式化程序管道输出,例如astyle?
答案 3 :(得分:0)
python Tools/Scripts/
目录中有一个脚本,主要用于修复整个python文件的缩进。但是,您可以轻松地稍微调整脚本并将其应用于代码段/行或其他类型的文件。
脚本也在线,在这里:
http://svn.python.org/projects/python/trunk/Tools/scripts/reindent.py
或者,作为这里的模块:
http://pypi.python.org/pypi/Reindent/0.1.0