Replace single character at given position

Bjoern Schliessmann usenet-mail-0306.20.chr0n0ss at
Tue Sep 19 23:43:01 CEST 2006

Martin Kulas wrote:

> From programming languages like C I expect something like that:
>>>> idx = 1
>>>> s1 = "pxthon"
>>>> s1[idx] = 'y'
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> TypeError: object does not support item assignment
> It does not work :-(

Yes, Python strings are immutable.
> Is this a typical approach in Python to replace one character
> in a string? Are there better (faster) ways to achieve my goal?

Is speed *really* your primary goal? :)

You could also convert the string to a list, do the changes, and
convert back.



BOFH excuse #259:

Someone's tie is caught in the printer, and if anything else gets
printed, he'll be in it too.

More information about the Python-list mailing list