[Tutor] string immutability
waynejwerner at gmail.com
Mon Oct 24 20:52:14 CEST 2011
On Mon, Oct 24, 2011 at 1:04 PM, 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?
> >>> s = "First"
> >>> print s.__class__
> <type 'str'>
> >>> print s
> >>> 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
>>> s = "First"
>>> s = "T"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Tutor