Mutable strings in Python
This will allow you to efficiently change characters in a string. Although you can't change the string length.
>>> import ctypes>>> a = 'abcdefghijklmn'>>> mutable = ctypes.create_string_buffer(a)>>> mutable[5:10] = ''.join( reversed(list(mutable[5:10].upper())) )>>> a = mutable.value>>> print `a, type(a)`('abcdeJIHGFklmn', <type 'str'>)
class MutableString(object): def __init__(self, data): self.data = list(data) def __repr__(self): return "".join(self.data) def __setitem__(self, index, value): self.data[index] = value def __getitem__(self, index): if type(index) == slice: return "".join(self.data[index]) return self.data[index] def __delitem__(self, index): del self.data[index] def __add__(self, other): self.data.extend(list(other)) def __len__(self): return len(self.data)
... and so on, and so forth.
You could also subclass StringIO, buffer, or bytearray.