a simple question about string object
Carl Banks
imbosol-1047873617 at aerojockey.com
Mon Mar 17 01:15:40 EST 2003
Frank Zheng wrote:
> Hi, all:
>
>>>> s = '12345'
>>>> s[2] = 'x'
> Traceback (most recent call last):
> File "<interactive input>", line 1, in ?
> TypeError: object doesn't support item assignment
>
> i know the string object is immutable, so if i want to do 'item assignment',
> i should do:
>>>> new_s = s[0:1] + 'x' + s[2:]
> ( i think it's ugly)
>
> Is there other ways to do this?
> should i define a function to do this? Is there any modules existing can do
> this?
The array module has arrays of characters, which you can use as a kind
of mutable string:
from array import array
s = array('c', '12345')
s[2] = 'x'
print s.tostring()
Problem is, most string operations don't work on character arrays.
--
CARL BANKS
More information about the Python-list
mailing list