Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Block Formatting

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)
like image 333
Kevin Li Avatar asked Apr 15 '26 18:04

Kevin Li


1 Answers

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.

like image 135
Tim Pietzcker Avatar answered Apr 18 '26 09:04

Tim Pietzcker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!