[Python-Dev] indented longstrings?

skip@pobox.com skip at pobox.com
Sat Nov 12 03:56:32 CET 2005


    Avi> Python's longstring facility is very useful, but unhappily breaks
    Avi> indentation. I find myself writing code like

    Avi>     msg = ('From: %s\r\n'
    Avi>            + 'To: %s\r\n'
    Avi>            + 'Subject: Host failure report for %s\r\n'
    Avi>            + 'Date: %s\r\n'
    Avi>            + '\r\n'
    Avi>            + '%s\r\n') % (fr, ', '.join(to), host, time.ctime(), err)
    Avi>     mail.sendmail(fr, to, msg)

This really belongs on comp.lang.python, at least until you've exhausted the
existing possibilities and found them lacking.  However, try:

    msg = ('From: %s\r\n'
           'To: %s\r\n'
           'Subject: Host failure report for %s\r\n'
           'Date: %s\r\n'
           '\r\n'
           '%s\r\n') % (fr, ', '.join(to), host, time.ctime(), err)

or

    msg = ('''\
From: %s
To: %s
Subject: Host failure report for %s
Date: %s

%s
') % (fr, ', '.join(to), host, time.ctime(), err)

or (untested)

    def istring(s):
        return re.sub(r"(\r?\n)\s+", r"\1", s)

    msg = """From: %s
             To: %s
             Subject: Host failure report for %s
             Date: %s

             %s
             """
    msg = istring(msg) % (fr, ', '.join(to), host, time.ctime(), err)

Skip


More information about the Python-Dev mailing list