Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 views
in Technique[技术] by (71.8m points)

python - How to indent the contents of a multi-line string?

I'm using the python cog module to generate C++ boilerplate code, and it is working great so far, but my only concern is that the resulting code, which is ugly by itself, is made worse by the fact that it's not indented. I'm too lazy to get the indentation right in the string generation function, so I'm wondering if there is a Python util function to indent the content of a multi-line string?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can indent the lines in a string by just padding each one with proper number of pad characters. This can easily be done by using the textwrap.indent() function which was added to the module in Python 3.3. Alternatively you could use the code below which will also work in earlier Python versions.

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:
')
print(indent(text, 4))

Result:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...