[Tutor] string immutability

Sander Sweers sander.sweers at gmail.com
Mon Oct 24 20:47:25 CEST 2011


On Mon, 24 Oct 2011, 20:04:20 CEST, Johan Martinez <jmartiee at gmail.com> wrote:

> I am struggling to understand Python string immutability. I am able to
> modify Python string object after initializing/assigning it a value. So
> how does immutability work? I am not following it. Sorry for really
> stupid question. Any help?

Mutibility means changinging the object (string) in place. What you are doing below is creating a new string and asigning it to a variable.
 
> <code>
> 
> > > > s = "First"
> > > > print s.__class__
> <type 'str'>
> > > > print s
> First
> > > > s = "Second"
> > > > print s
> Second
> > > > 
> 
> </code>

If the object s reffernces is mutable you should be able to do:

s[0] = 'x'

Try it and see what happen. Then also try this with a list of strings 

s = ['f', 'i', 'r', 's', 't']
s[0] = 'x'

Greets
sander
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20111024/b2093b85/attachment-0001.html>


More information about the Tutor mailing list