How to modify a string in place?

Michael Hudson mwh21 at cam.ac.uk
Fri May 14 12:45:16 EDT 1999


"John Powers" <jpowers at acm.org> writes:
> I have read a large binary image of a program into a Python string and need
> to patch hundreds of places in the string to reflect relocated addresses.
> Since strings are immutable, I wind up cutting the string apart (beforehole
> = image[:hole]; afterhole = image[hole+4:]) then reconstructing the image
> (image = beforehole + reloc + afterhole). This is extremely slow!
> 
> I would like to modify the string in place. Any ideas?

1) Use StringIO. It allows you to treat strings as files, so you can
   .seek() to a position, then .write().

2) Actually use cStringIO, it's pretty much the same as StringIO, but
   implemented in C, and hence much quicker.

If you do this

try:
    import cStringIO
    StringIO = cStringIO
except ImportError:
    import StringIO

you get the quickest implementation available.

HTH Michael




More information about the Python-list mailing list