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

Anthony Baxter anthony at interlink.com.au
Wed Jun 25 12:30:39 EDT 2003


>>> 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
> #-------------------------------------

Instead, build up a list of strings, then join them all at
the end - this way, the system only has to allocate the
space once. Much quicker.

 #---------------------------------
 htmlPage = []
 htmlPage.append("<html><header></header><body>")
 htmlPage.append("more html")
 ...
 htmlPage.append("even more html")
 ...
 htmlPage.append("</body></html>")
 page = ''.join(htmlPage)
 print page
 #-------------------------------------

Anthony





More information about the Python-list mailing list