Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I want to make this code:

def usage():

    print(
        """
Usage examples:

Test deployment:
       $ fab [noinput] test deploy

Staging deployment:
       $ fab [noinput] staging deploy

Production deployment:
       $ fab [noinput] production deploy
""")

to look more like this:

def usage():

    print(
        """
        Usage examples:
        Test deployment:
            $ fab [noinput] test deploy
        Staging deployment:
            $ fab [noinput] staging deploy
        Production deployment:
            $ fab [noinput] production deploy
        """
    )

but this give different results. What is the best way of writing this?

share|improve this question

2 Answers 2

up vote 20 down vote accepted

You can use textwrap.dedent to remove common whitespace from the start of all lines in a multiline string:

>>> import textwrap
>>> print(textwrap.dedent(
        """
        Usage examples:
        Test deployment:
            $ fab [noinput] test deploy
        Staging deployment:
            $ fab [noinput] staging deploy
        Production deployment:
            $ fab [noinput] production deploy
        """
))

Usage examples:
Test deployment:
    $ fab [noinput] test deploy
Staging deployment:
    $ fab [noinput] staging deploy
Production deployment:
    $ fab [noinput] production deploy

As it says in the docs:

This can be used to make triple-quoted strings line up with the left edge of the display, while still presenting them in the source code in indented form.

share|improve this answer
4  
+1 this is awesome, thanks! –  janos Aug 18 at 12:50

For smaller pieces of text, I tend to just close the double quotes and open them on the next line. Then you'll have to add the newlines yourself using \n though:

print(
    "Usage examples:\n"
    "Test deployment:\n"
    "    $ fab [noinput] test deploy\n"
    "Staging deployment:\n"
    "    $ fab [noinput] staging deploy\n"
    "Production deployment:\n"
    "    $ fab [noinput] production deploy\n"
)
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.