Search code examples
pythonstringtextindentationword-wrap

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?


Solution

  • 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    ')