How do I indent a multiline string in the context of string formatting? e.g.
'''
<
%s
>
''' % (paragraph)
where paragraph contains newlines. ('foo\nbar')
If I use the above code, I get output like this:
'''
<
foo
bar
>
'''
when I really want this:
'''
<
foo
bar
>
'''
I know I could do something like:
'''
<
%s
>
''' % (paragraph)
but this breaks readability for my purposes.
I also realize I could just write some code to indent all but the first line by 1 indent, but this isn't really an extensible solution (what if I have 2 indents? or 3? etc.)
EDIT: Before you post an answer, consider how your solution works with something like this:
'''
<
%s
<
%s
%s
<
%s
>
>
>
''' % (p1, p2, p3, p4)
How about this:
'''
<
%s
>
''' % ("\n ".join(paragraph.split("\n")))
Result:
<
foo
bar
>
The string used in the .join() method must contain the same whitespace (plus a \n at the start) as whatever comes before %s in your string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With