multiline snippets with triple quotes

Christopher T King squirrel at WPI.EDU
Thu Aug 12 16:06:58 EDT 2004


On Thu, 12 Aug 2004, Christoph Zwerschke wrote:

> So, what would be the pythonic way to implement such multiline snippets?

The textwrap.dedent() function is provided for just this purpose:

 from textwrap import dedent

 if output == html:
     snip =  dedent('''\
                     <html>
                     <head><title>Hello, World</title></head>
                     <body bgcolor="aqua"><h1>What's up?</h1>
                     </html>''')
 else:
     snip = 'Hello!'

textwrap.dedent() removes uniform indentation from the beginning of each 
line in the string, so you can still insert desired indents in a natural 
way.  Note the backslash after the opening quote, and how the actual 
string starts on the next line: dedent() isn't as smart as pydoc when it 
comes to uniformly indenting strings; it doesn't know to skip the first 
line (this helps with more general usage, though).




More information about the Python-list mailing list