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

Gerrit Holl gerrit at nl.linux.org
Wed Jun 25 17:23:51 EDT 2003


Gobo Borz wrote:
> 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.

Another way, which has not yet been mentioned but which I like much,
is the cStringIO module. You can write to a string as if it is a
file:

  0 >>> import cStringIO
  1 >>> mystr = cStringIO.StringIO()
  2 >>> mystr.write("<html")
  3 >>> mystr.write("<body>")
  4 >>> mystr.write("<h1>Header</h1>")
  5 >>> mystr.write("<p>Hello, world!</p>")
  6 >>> mystr.write("</body></html>")
 10 >>> mystr.getvalue()
'<html<body><h1>Header</h1><p>Hello, world!</p></body></html>'

The cStringIO module is documented at:

http://www.python.org/dev/doc/devel/lib/module-StringIO.html

cStringIO is a faster C implementation with the same API.

yours,
Gerrit.

-- 
196. If a man put out the eye of another man, his eye shall be put out.
        -- 1780 BC, Hammurabi, Code of Law
--
Asperger Syndroom - een persoonlijke benadering:
	http://people.nl.linux.org/~gerrit/
Het zijn tijden om je zelf met politiek te bemoeien:
	http://www.sp.nl/





More information about the Python-list mailing list