Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 913
lurscher Avatar asked Nov 22 '11 21:11

lurscher


People also ask

How do you indent multiple lines?

If you prefer using [spacebar] to indent your code rather than using [tab], you can select multiple lines by holding the [alt] key and clicking on the beginning of each line you want to indent. Then, you can press [spacebar] and all the selected lines will be affected. omg it moves!

How do you change the indent of multiple lines in Python?

Every code editor worth its salt has a one-key way to indent and dedent blocks. In IDLE (the IDE included with Python), CTRL + [ dedents and CTRL + ] indents. Selecting text then using the shift+tab shortcut also works if you're using the Python editor built into Canopy on Windows.

How do I format a multiline string in Python?

In Python, you have different ways to specify a multiline string. You can have a string split across multiple lines by enclosing it in triple quotes. Alternatively, brackets can also be used to spread a string into different lines. Moreover, backslash works as a line continuation character in Python.


2 Answers

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 
like image 169
martineau Avatar answered Oct 04 '22 14:10

martineau


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') 
like image 44
ThorSummoner Avatar answered Oct 04 '22 15:10

ThorSummoner