amontalenti / elements-of-python-style

Goes beyond PEP8 to discuss what makes Python code feel great. A Strunk & White for Python.
3.44k stars 260 forks source link

Suggest using `textwrap.dedent()` to keep indentation even with triple-quote multi-line strings #26

Open maxalbert opened 8 years ago

maxalbert commented 8 years ago

In section "Implicit multi-line strings vs triple-quote """" you can get the best of both worlds (avoiding ugly new-lines as well as keeping indentation) by using textwrap.dedent(), for example:

from textwrap import dedent

msg = dedent("""Hello, wayward traveler!
                What shall we do today?
                =>""")
print(msg)

You can also achieve more compact spacing if you start the string in the second line (but then you need to add a backslash after the opening triple-quote to avoid a leading newline):

import textwrap

msg = textwrap.dedent("""\
    Hello, wayward traveler!
    What shall we do today?
    =>""")
print(msg)

I slightly prefer the second one, but I guess it's a matter of taste.

amontalenti commented 8 years ago

@maxalbert Thanks for this suggestion. I'll think about adding a reference to this to the guide.

olivren commented 5 years ago

The first form does not work, because dedent only removes common leading white space. Here, there is no common leading whitespace, because the first line has no leading whitespace at all.

maxalbert commented 5 years ago

Good catch @olivren, thanks for pointing this out. (I'm surprised I didn't re-execute the snippets when posting this to ensure they both behaved correctly. 😂)