Python formatting formatting

What is the best way to format a large chunk of text in python? I do not mean formatting the output, but rather for readability. I'm trying to follow the guidelines for python layout , but I don't see any comments on how to format large 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: """ 

A large block of text looks terrible and has no indentation of 4 spaces, so it is difficult to read.

What I would like to see:

  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 a space at the beginning of the output.

Any ideas on how I can do this follow the recommended layout for python? I would like it to be neat and easy to read.

Is it possible to do this without printing for each line? eg.

 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 was the way we would like the code to appear without resorting to printing on each line.

+8
python string-formatting
source share
5 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: """) 
+17
source share

Adjacent string literals are concatenated automatically.

 >>> 'x' 'y' 'xy' 
+1
source share

I usually do something like this:

 print '\n'.join([ '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:', ]) 

Since it allows you to (relatively) easily rebuild and add new lines.

+1
source share
 print("first line\n" "second line\n" "first part of third line" "rest of third line\n") 

I do this often for very long lines.

0
source share

You can use your favorite indentation and subsequently delete the tabs:

 def getCalendar(): return ''' Text here Text here Text here Text here '''.replace('\t', '') 
0
source share

All Articles