Python multi-line string literals with textwrap.dedent()

You’re writing some Python, and you need to write out a string containing newlines. You’ve got two options: a regular string with \n in it, or a multi-line string literal using three double quotes (are those sextuple quotes?), which looks like this:

my_string = """This
is a
multi-line string"""
assert my_string == "This\nis a\nmulti-line string"

But you’ve got a problem. The point in your code where you’re putting the string is indented, and those indents are showing up in your string, like this:

def get_string():
return """This
is a
multi-line string"""
assert get_string() == "This\n is a\n multi-line string"

There’s a handy function in the standard library for this called textwrap.dedent(). It removes common leading whitespace from lines in the input. So you put that around your string, but it doesn’t help!

def get_string():
return textwrap.dedent("""This
is a
multi-line string""")
assert get_string() == "This\n is a\n multi-line string"

You might have noticed that the first line, This does not have leading whitespace! You could manually add that leading whitespace, but there’s a better way: what if the first line of the string was actually on the next (indented) line? We can use the backslash as a line continuation character immediately after the opening quotes:

def get_string():
return """\
This
is a
multi-line string"""
assert get_string() == " This\n is a\n multi-line string"

Now that they all share the leading whitespace, textwrap.dedent() will do the right thing:

def get_string():
return textwrap.dedent("""\
This
is a
multi-line string""")
assert get_string() == "This\nis a\nmulti-line string"

See the docs for textwrap.dedent() here.

Cloud Robotics Research Scientist at @iRobot