a simple question about string object
timr at probo.com
Mon Mar 17 07:29:16 CET 2003
"Frank Zheng" <hust_zxq524 at 263.net> wrote:
>>>> 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)
It's also wrong:
new_s = s[0:2] + 'x' + s[3:]
Better yet is:
new_s = "%sx%s" % (s[0:2],s[3:])
>Is there other ways to do this?
>should i define a function to do this? Is there any modules existing can do
There is no standard module to do this. If you need to do this a lot, you
can just convert the string to a list and manipulate the list:
Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> s = '12345'
>>> s_lst = list(s)
>>> s_lst = 'x'
['1', '2', 'x', '4', '5']
>>> s = ''.join(s_lst)
- Tim Roberts, timr at probo.com
Providenza & Boekelheide, Inc.
More information about the Python-list