Python: Manipulate string or binary bytes with StringIO

November 25th, 2008 mysurface Posted in Developer, python | Hits: 187518 | 6 Comments »

Sometimes it is not convenient to construct string using equal (=) like this:

str = "Hello, "
...
str = str + "my name is "
...
str = str + Name
print str

In python, we have string stream (StringIO) that will behave like file stream, you can construct your string like this:

str=StringIO()
...
str.write("Hello, ")
...
str.write("my name is ")
...
str.write(Name)
print str.getvalue()

The same way, you can construct your binary bytes with StringIO and write it into file once you are done.


bin=StringIO()
bin.write("/x5F/x5F%c" % 0xFF)
...
file = open ("my.bin","wb")
file.write(bin.getvalue())
file.close()

6 Responses to “Python: Manipulate string or binary bytes with StringIO”

  1. To import the StringIO Class:

    from StringIO import StringIO

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

  2. Thanks André, forgot to mention how to import StringIO. :P

  3. i usually use

    str = ”
    str += ‘line 1\n’
    str += ‘line 2\n’
    str += ‘%s’ % 12345

    shorter :)

  4. Unfortunately this forum is vulnerable to cheesy FFF spambots,
    although at least it seems that the links have been filtered out. Attaboy.

  5. Thanks for pointing out, I was not aware about this previously.

  6. It’s amazing to pay a visit this web page and reading the views of all colleagues regarding this article,
    while I am also eager of getting knowledge.

Leave a Reply