[Tutor] MutableString/Class variables

Steven D'Aprano steve at pearwood.info
Fri May 10 13:28:57 CEST 2013


On 09/05/13 22:10, Albert-Jan Roskam wrote:
> Hello,
>
> I was just playing a bit with Python and I wanted to make a mutable string, that supports item assignment. Is the way below the way to do this?


Guido's time machine strikes again:

py> from UserString import MutableString
py> s = MutableString("Hello world!")
py> s[-1] = '?'
py> print s
Hello world?


You can see the source code here:

http://hg.python.org/cpython/file/2.7/Lib/UserString.py

and the docs:

http://docs.python.org/2/library/userdict.html#module-UserString


Note, however, that MutableString is (allegedly) very inefficient, and has been removed from Python 3.x. (It seems to me that it cannot possibly be that much more inefficient than using immutable strings. It's just a wrapper around an immutable string with a few convenience methods.)

But really, unless you are dealing with truly humongous strings, you're better off just sticking to the standard Python built-in string (unicode) type. And if by chance you really do need a mutable string-like data structure, you probably should look at something like ropes, implemented in C or Cython.

http://en.wikipedia.org/wiki/Rope_(data_structure)



-- 
Steven


More information about the Tutor mailing list