str and __setitem__

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Thu Jan 25 05:58:43 EST 2007


On Thu, 25 Jan 2007 10:16:31 +0000, Tor Erik Soenvisen wrote:

> Hi,
> 
> What do I need to do to make the code below work as expected:

Use another language *wink*

Python strings are immutable, you can't change them in place.

> class str2(str):
> 
> 	def __setitem__(self, i, y):
> 		assert type(y) is str
> 		assert type(i) is int
> 		assert i < len(self)
> 		self = self[:i] + y + self[1+i:]

This line rebinds a NEW string to the name "self" -- it doesn't change the
contents of the original string. Because the name self is local to the
method, it doesn't change references to the original string.

Are you sure you need mutable strings? 

Here are a few different ways of getting something like a mutable string:

* use the MutableString class from the UserString module;

* use the mmap module;

* use lists of characters instead of strings;


-- 
Steven




More information about the Python-list mailing list