a simple question about string object
peter at engcorp.com
Mon Mar 17 04:53:41 CET 2003
Frank Zheng wrote:
> Hi, all:
> >>> s = '12345'
> >>> s = '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
If this is all you're doing with the string, and you use the string
as an immutable string for the usual string purposes most of the time,
then this isn't ugly, it's just what you need to do to work with
immutable data types. You'd do exactly the same thing if you
had a tuple and you thought you needed to modify it.
More likely, you are thinking of your data as a string only because
at some point you want to output it that way, but most of the time
you are manipulating it as a list of characters, in which case you
should focus on the mutability part and do what Greg suggested:
use a list, convert to a string only for output.
More information about the Python-list