multiline snippets with triple quotes

Christoph Zwerschke cito at online.de
Thu Aug 12 15:12:24 EDT 2004


I sometimes use triple quotes in order to produce snippets of multiline
code, like that:

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

This has the advantage that you don't need to care for inserting newlines
and escaping quotes and is very readable.

However, the triple quoted strings will also contain the indentation of the
Python block. It would not really matter here, since whitespace is ignored
in this case, but there could be situations where whitespace at the
beginning of the lines would matter, and it simply makes no sense to carry
over the identation in most cases.

Of course, I could simply unindent the triple quoted snippets, but then the
Python code starts to become unreadable, if you have many of such snippets
in deeply indented blocks. And isn't bad indentation something that Python
usually forbids "by force" even?

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

Gtx
Chris





More information about the Python-list mailing list