Live Chat!

Python: Manipulate string or binary bytes with StringIO

2 votos Vota!!

November 25th, 2008 mysurface Posted in Developer, python | Hits: 145276 |

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()

13 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. It’s ok to have a comment.

  5. The best is not always the most popular. My favorite scientific blogs. Thank you admin.

  6. This report is misleading. Luda doesn’t claim to have hoes on Midway or Wake Islands, only in area code 808, which also includes Hawaii, a far more likely zone for hoes, it seems.

  7. Thank you for adding

  8. Thank you for adding

  9. Thank you for adding

  10. Thank you for adding

  11. u have a nice site i was searching about the popular site of your countr i found here. good workingz

  12. u have a nice site i was searching about the popular site of your countr i found here. good workings

  13. tanks for you adminbey

Leave a Reply

Security Code: