Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Indent all lines of a string except first while preserving linebreaks?

I want to indent all lines of a multi-line string except the first, without wrapping the text.

For example, I want to turn:

A very very very very very very very very very very very very very very very very
long mutiline
string

into:

A very very very very very very very very very very very very very very very very
     long multiline
     string

I have tried

textwrap.fill(string, width=999999999999, subsequent_indent='   ',)

But this still puts all of the text on one line. Thoughts?

like image 452
David Y. Stephenson Avatar asked Aug 29 '13 18:08

David Y. Stephenson


People also ask

How do you indent all lines in Python?

Highlight/ select the lines you want indented, then press TAB as often as needed until they reach the proper indent level. You can remove spaces with SHIFT TAB . You can also use CTRL+ALT+I to auto-indent the selection.

How do I get rid of the extra indentation in Python?

If you want to remove indentation that is common to the whole multiline string, use textwrap. dedent().

How do you wrap text in Python?

wrap(text, width=70, **kwargs): This function wraps the input paragraph such that each line in the paragraph is at most width characters long. The wrap method returns a list of output lines. The returned list is empty if the wrapped output has no content.


1 Answers

You just need to replace the newline character '\n' with a new line character plus the white spaces '\n    ' and save it to a variable (since replace won't change your original string, but return a new one with the replacements).

string = string.replace('\n', '\n    ')
like image 105
Bonifacio2 Avatar answered Oct 16 '22 22:10

Bonifacio2