Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Python (http://www.velocityreviews.com/forums/f43-python.html)
-   -   RE: better way than: myPage += 'more html' , ... (http://www.velocityreviews.com/forums/t318858-re-better-way-than-mypage-more-html.html)

Delaney, Timothy C (Timothy) 06-26-2003 12:30 AM

RE: better way than: myPage += 'more html' , ...
 
> From: Gerrit Holl [mailto:gerrit@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/...-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)



All times are GMT. The time now is 02:35 AM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.