Tuesday, October 19, 2010

Python string manipulation problem

In python string are immutable so if you want to just change a character in a string you get following error :

>>>> idx = 1
>>>> s1 = "pxthon"
>>>> s1[idx] = 'y'

> Traceback (most recent call last):
> File "", line 1, in ?
> TypeError: object does not support item assignment



But you can always go for a way out which is not pretty and can lead to some problems if you are not careful, but works :

s1 = s1[0:idx] + 'y' + s1[idx+1:]

No comments: