better way than: myPage += 'more html' , ...
Delaney, Timothy C (Timothy)
tdelaney at avaya.com
Wed Jun 25 20:30:21 EDT 2003
> From: Gerrit Holl [mailto:gerrit at nl.linux.org]
>
> 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.
Indeed, the following might make things nice and easy for you ...
import cStringIO as StringIO
# Subclass of str so that it can be used nearly anywhere that requires a real
# string.
class MutableString (str):
def __init__ (self, s=""):
super(MutableString, self).__init__()
self.data = StringIO.StringIO()
self.data.write(s)
def __add__(self, s):
m = MutableString(self.data.getvalue())
m.data.write(s)
return m
def __iadd__(self, s):
self.data.write(s)
return self
def __str__(self):
return self.data.getvalue()
def __repr__(self):
return repr(str(self))
s = MutableString("Hello,")
s += " world!"
print s
print repr(s)
More information about the Python-list
mailing list