str and __setitem__
bearophileHUGS at lycos.com
bearophileHUGS at lycos.com
Thu Jan 25 06:06:42 EST 2007
Peter Otten:
> >>> class mutable_str(object):... def __init__(self, value):
> ... self._value = value
> ... def __setitem__(self, index, value):
> ... self._value = self._value[:index] + value +
> self._value[index+1:]
> ... def __str__(self):
> ... return self._value
> ...>>> a = mutable_str("123")
> >>> a[1] = "x"
> >>> print a
For this purpose an array may be better, if you have to change it often
and print is only once in a while:
from array import array
a = array("c", "123")
a[1] = "x"
print a
The OP can also use a class, if some other methods are needed:
from array import array
class mutable_str(object):
def __init__(self, value):
self._value = array("c", value)
def __setitem__(self, index, value):
self._value[index] = value
def __str__(self):
return self._value.tostring() # this requires time
a = mutable_str("123")
a[1] = "x"
print a
Probably array.array can be subclassed too...
bye,
bearophile
More information about the Python-list
mailing list