Replace single character at given position

Magnus Lycka lycka at carmen.se
Wed Sep 27 06:04:16 EDT 2006


Larry Bates wrote:
>> How do I replace a single character in a string at a given position?

You can't. Strings can't be mutated in Python how ever hard you try.
The string type is immutable. (Of course, I suspect you can write a
horrible C extension that would help you cheat. Yuk!)

You need to create a *new* string object with the properties you like.
This is what you do below. As soon as you use "s1=...", you are
rebinding "s1" to a (typically) different string object than it was
bound to before.

If you think about this, it will probably also answer the "does Python
use call by reference or call by value" questions that will eventually
pop up in your head if you come from C.

>> From programming languages like C I expect something like that:

What you need to realize is that objects and assignments are
different in Python and in C. In C, "a=x" basically means "put
the value identified by x in the location defined by a". In
Python, "a=x" basically means "bind the name a to the object
identified by x". See http://pyref.infogami.com/naming-and-binding

> 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)

Both these examples creates new string objects and rebind the
name s1 to these new objects. In other words, if you had "s2=s1"
on a previous line, the expression "s1==s2" will be false after
the code above has been executed.



More information about the Python-list mailing list