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

Why not pipe the output through a command-line code formatter such as astyle?


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:\n')
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

If you have a leading newline:

Heredocs can contain a literal newline, or you can prepend one.

indent = '    '

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

Here is it shown in pprint dump:

>>> pprint(indented)

' Hello\n World\n '

Awkward, but works


If you do not have a leading newline:

indent = '    '

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

Optional, trim first newline and trailing spaces/tabs

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