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

Andy Jewell andy at wild-flower.co.uk
Wed Jun 25 13:30:14 EDT 2003


On Wednesday 25 Jun 2003 5:20 pm, Gobo Borz wrote:
> Hi everyone,
>
> I have a python cgi program that uses print statements to write html.
> The program has grown, and for reasons I won't bore you with, I need to
> build the page in a string and "print" it at once.
>
> 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
> #-------------------------------------
>
> Thanks, Gobo


An easy way, which requires little changes tou your code would be to use a 
list and join it up into a string in one go at the end:

-----------8<--------------
htmlPage=["<html><header></header><body>\n"]
htmlPage.append("more html\n")
....
htmlPage.append("more html\n")
....
htmlPage.append("<\body><\html>\n")
htmlDoc="".join(htmlPage)
-----------8<--------------

This is more efficient, as the string joining is done all at the same time, 
rather than in little chunks.

hope that helps
-andyj






More information about the Python-list mailing list