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

Discussion in 'Python' started by Delaney, Timothy C (Timothy), Jun 26, 2003.

  1. > From: Gerrit Holl [mailto:]
    >
    > 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)
    Delaney, Timothy C (Timothy), Jun 26, 2003
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Gobo Borz
    Replies:
    11
    Views:
    1,065
    Chuck Spears
    Jun 26, 2003
  2. Replies:
    0
    Views:
    652
  3. Peter Bencsik
    Replies:
    2
    Views:
    810
  4. Steven D'Aprano
    Replies:
    0
    Views:
    75
    Steven D'Aprano
    Dec 23, 2013
  5. Replies:
    2
    Views:
    42
    Mark H Harris
    May 13, 2014
Loading...

Share This Page