Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
maxalbert opened this issue Jan 9, 2016 · 3 comments

Comments

@maxalbert
Copy link

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
Copy link
Owner

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

@olivren
Copy link

olivren commented Jul 11, 2019

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
Copy link
Author

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. 😂)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants