Replace single character at given position

Larry Bates larry.bates at websafe.com
Tue Sep 19 17:55:13 EDT 2006


Martin Kulas wrote:
> Hello!
> 
> How do I replace a single character in a string at a given position?
> 
> 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 :-(
> 
> My second attempt succeeds:
> 
>>>> s1 = s1[0:idx] + 'y' + s1[idx+1:]
>>>> s1
> 'python'
> 
> 
> Is this a typical approach in Python to replace one character
> in a string? Are there better (faster) ways to achieve my goal?
> I have looked through the methods of type ``string''
> but I have not found any appropriate method or function.
> 
> Thanks in advance,
> Martin
> 
> 
> 
You can do this:

s1=s1.replace('x','y', 1) # Only replace the first x with y

or

s1l=list(s1)
s1l[1]='y'
s1=''.join(s1l)

or your method of using slices.

All depends on what you want to do.  Quite often you use
.replace() method so you don't have to worry with the index.

-Larry Bates



More information about the Python-list mailing list