# Avoiding Python multiline string indentation

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?

-

## 3 Answers

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.

-
+1 this is awesome, thanks! –  janos Aug 18 '14 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"
)

-

When I need some usage-text or help-text about a program or module, there is another option, at the begin of the source code:

#!/bash/python
"""
Usage examples, Test deployment,
and any other text you like
"""


And when I need to print it somewhere in the program:

print(__doc__)

-
very good idea! +1 :) –  noisy Dec 9 '14 at 11:16