Last Updated: February 25, 2016
·
510
· tlatsas

readable multi-line strings in python

Multi-line strings in python can get handy, but the extra whitespace that is preserved may be a problem.

The first (ugly) solution is to write multi-line strings without indentation like so:

def foo(my_dict):
    config = """USER={username}
SERVICENAME=
DEMAND=no
DNSTYPE=NOCHANGE
USERCTL=no
FIREWALL=NONE
ETH={interface}
LCP_INTERVAL=10
LCP_FAILURE=3
PIDFILE=/var/run/pppoe
CLAMPMSS=no
PPPOE_TIMEOUT=20
DEFROUTE=YES""".format(**my_dict)

    return config

However, this is ugly and a little bit unreadable. A better way is to indent the string and then use the textwrap module to remove tha extra whitespace:

import textwrap

def foo(my_dict):
    config = """\
            USER={username}
            SERVICENAME=
            DEMAND=no
            DNSTYPE=NOCHANGE
            USERCTL=no
            FIREWALL=NONE
            ETH={interface}
            LCP_INTERVAL=10
            LCP_FAILURE=3
            PIDFILE=/var/run/pppoe
            CLAMPMSS=no
            PPPOE_TIMEOUT=20
            DEFROUTE=YES
            """.format(**my_dict)

    config = textrwap.dedent(config)
    return config

Documentation: http://docs.python.org/2/library/textwrap.html#textwrap.dedent