Multi-Line Strings: A Modest Proposal

Lawrence D’Oliveiro lawrencedo99 at gmail.com
Sat Aug 13 20:38:11 EDT 2016


Python allows a single string literal to cross multiple lines, provided it begins and ends with three quote characters, e.g.

    s = """this string continues
    on the next line."""

There is a drawback with this: any whitespace at the start of the continuation line is included as part of the string:

    >>> print(s)
    this string continues
        on the next line.

So really, you should write it more like

    s = """this string continues
on the next line."""

which gets a bit ugly.

Python has quite a different convention for its compound statements, which can (and usually do) continue across multiple lines: and that is the use of indentation to denote nesting.

So I propose adapting this convention to triply-quoted strings, as follows: lines where the string literal continues must begin with the *same* initial whitespace as the line where the string started. This initial whitespace is stripped off before including the rest as part of the string. Any additional whitespace after that at the start of the line becomes part of the string. So the first example would now print as

    >>> print(s)
    this string continues
    on the next line.

which looks more like what was intended.



More information about the Python-list mailing list