How to modify a string in place?

Darrell news at dorb.com
Fri May 14 17:57:33 EDT 1999


John Powers <jpowers at acm.org> wrote in message
news:7hhi8e$jkf$1 at tilde.csc.ti.com...
> 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!
>

Had this same problem and solved this way. Changes are batched in a list
then until the end of processing. The problem I had was the string was 4meg+
with many thousands of replacements and deletions.

--Darrell

def insertListDelete(inbuf, l):
        """ Insert and delete segments in a buffer
        l is a list of (start, newString, end) The input 'l' must be sorted
on start
        If start and end are equal then newString is inserted at that point
        If end > start then this range is deleted and newString inserted
        If end < start then this range is duplicated. Haven't tried this
one.
        """
        splitBuf=[]
        last=0
        append=splitBuf.append
        for i in l:
                b=inbuf[last:i[0]]
                append(b)
                append(i[1])
                last=i[2]       # Advance past some buffer here
        append(inbuf[last:])
        return string.join(splitBuf,'')







More information about the Python-list mailing list