On Mon, Oct 24, 2011 at 1:52 PM, Wayne Werner <waynejwer...@gmail.com>wrote:
> On Mon, Oct 24, 2011 at 1:04 PM, Johan Martinez <jmart...@gmail.com>wrote: > >> Hi, >> >> 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? >> >> <code> >> >> >>> s = "First" >> >>> print s.__class__ >> <type 'str'> >> >>> print s >> First >> >>> s = "Second" >> > > This is not actually modifying the string object. Unlike most other > programming languages where a variable refers to an actual location in > memory (usually), in Python the variable names the actual value. > > So when you do s = "First" then you are telling python that you want to be > able to refer to the string "First" by the name/variable s. > > When you execute s="Second" you are now telling python that instead of > referring to "First" you want the name 's' to refer to the string "Second". > > If you try to modify the actual value of the string, you will raise an > exception: > > >>> s = "First" > >>> s[0] = "T" > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > TypeError: 'str' object does not support item assignment > > HTH, > Wayne > Thanks for the replies everyone - Steve, Dave, Sander and Wayne. I realized my wrong understanding/interpretation after posting the message to the list, which usually happens most of the time with me! jM.
_______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor