簡體   English   中英

如何縮進多行字符串的內容?

[英]How to indent the contents of a multi-line string?

我正在使用 python cog模塊來生成 C++ 樣板代碼,到目前為止它運行良好,但我唯一擔心的是生成的代碼本身很丑,因為它沒有縮進而變得更糟。 我懶得在字符串生成函數中正確縮進,所以我想知道是否有一個 Python util 函數來縮進多行字符串的內容?

您可以通過用適當數量的填充字符填充每一行來縮進字符串中的行。 這可以通過使用在 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

如果你有一個領先的換行符:

Heredocs 可以包含一個文字換行符,或者您可以預先添加一個。

indent = '    '

indent_me = '''
Hello
World
''' 
indented = indent_me.replace('\n', '\n' + indent)
print(indented)

這是它在 pprint 轉儲中顯示的:

>>> pprint(縮進)

' Hello\\n World\\n '

尷尬,但有效


如果您沒有前導換行符:

indent = '    '

indent_me = '''\
Hello
World
''' 
indented = indent + indent_me.replace('\n', '\n' + indent)
print(indented)

可選,修剪第一個換行符和尾隨空格/制表符

.lstrip('\n').rstrip(' \t')

為什么不通過命令行代碼格式化程序(例如 astyle)來管道輸出?

在 python Tools/Scripts/目錄中有一個腳本,主要用於修復整個 python 文件的縮進。 但是,您可以輕松地稍微調整腳本並將其應用於代碼段/行或其他類型的文件。

該腳本也位於網上,在這里:
http://svn.python.org/projects/python/trunk/Tools/scripts/reindent.py

或者,作為此處的模塊:
http://pypi.python.org/pypi/Reindent/0.1.0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM