Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Formatting Large Text

What's the best way to format a large blob of text in python? I don't mean formatting the output, but rather for readability. I've been trying to follow the guidelines for python layout, but I don't see any remarks on how to format a large blob of text.

For example:

class GenerateCalendar(object):
def __init__(self):
    super( GenerateCalendar, self ).__init__()

def getCalendarHeader( self ):
    print """
BEGIN:VCALENDAR
PRODID:-//Atlassian Software Systems//Confluence Calendar Plugin//EN
VERSION:2.0
CALSCALE:GREGORIAN
X-WR-CALNAME;VALUE=TEXT:
X-WR-CALDESC;VALUE=TEXT:
"""

The large block of text looks terrible and it's not indented by 4 spaces, so it's hard to read.

What'd I'd like to see is:

 def getCalendarHeader( self ):
    print """
    BEGIN:VCALENDAR
    PRODID:-//Atlassian Software Systems//Confluence Calendar Plugin//EN
    VERSION:2.0
    CALSCALE:GREGORIAN
    X-WR-CALNAME;VALUE=TEXT:
    X-WR-CALDESC;VALUE=TEXT:
    """

but this introduces white space to the beginning of the output.

Any ideas on how I can make this follow the recommended layout for python? I'd like to keep it neat and easy to read.

Is it possible to do so without doing a print for each line? e.g.

def getCalendarHeader( self ):
    print "BEGIN:VCALENDAR\n"
    print "PRODID:-//Atlassian Software Systems//Confluence Calendar Plugin//EN\n"
    print "VERSION:2.0\n"
    print "CALSCALE:GREGORIAN\n"
    print "X-WR-CALNAME;VALUE=TEXT:\n"
    print "X-WR-CALDESC;VALUE=TEXT:\n"

The above is the way I'd like to have the code appear, without resorting to doing a print on each line.

like image 750
petebowden Avatar asked Feb 15 '12 21:02

petebowden


1 Answers

The standard library has tools for this:

import textwrap

#...

    def getCalendarHeader(self):
        print textwrap.dedent("""\
            BEGIN:VCALENDAR
            PRODID:-//Atlassian Software Systems//Confluence Calendar Plugin//EN
            VERSION:2.0
            CALSCALE:GREGORIAN
            X-WR-CALNAME;VALUE=TEXT:
            X-WR-CALDESC;VALUE=TEXT:
            """)
like image 115
Ned Batchelder Avatar answered Nov 15 '22 18:11

Ned Batchelder