better way than: myPage += 'more html' , ...

mirko-lists at zeibig.net mirko-lists at zeibig.net
Wed Jun 25 20:48:31 CEST 2003


In article <3EF9CBCB.90305 at yahoo.com>, Gobo Borz wrote:
> I remember reading somewhere that building the string with successive 
> "+=" statements is inefficient, but I don't know any alternatives, and 
> my search attempts came up empty. Is there a better, more efficient way 
> to do it than this:
> 
> #---------------------------------
> htmlPage = "<html><header></header><body>"
> htmlPage += "more html"
> ...
> htmlPage += "even more html"
> ...
> htmlPage += "</body></html>"
> print htmlPage
> #-------------------------------------
Hello Gobo,

you may use the list solution provided in the former chapters. Some other
solution would be to use string substitution:
--------- snip -----------
htmlPage = """
<html>
    <head>
        <title>%(title)s</title>
    </head>
<body>
    <h1>%(title)s</h1>
    %(body)s
</body>
</html>
"""

body = []
body.append("<p>my first snippet</p>")
body.append("<ul>")
for in range(10):
    body.append("""<li>%s. entry</li>""" % i)
body.append("</ul>")

contents = { "title": "My Foopage",
             "body": "\n".join(body) }

print htmlPage % contents
-------- snap -------------

This type of substitution goes for a very simple templating system.

Best Regards
Mirko





More information about the Python-list mailing list