<br><br><div class="gmail_quote">On Mon, Oct 24, 2011 at 1:52 PM, Wayne Werner <span dir="ltr"><<a href="mailto:waynejwerner@gmail.com">waynejwerner@gmail.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">
<div class="gmail_quote"><div><div></div><div class="h5">On Mon, Oct 24, 2011 at 1:04 PM, Johan Martinez <span dir="ltr"><<a href="mailto:jmartiee@gmail.com" target="_blank">jmartiee@gmail.com</a>></span> wrote:<br>
<blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
<div>Hi,</div><div><br></div><div>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? </div>
<div><br></div><div><code> </div><div><br></div><div>>>> s = "First"</div><div>>>> print s.__class__</div><div><type 'str'></div><div>>>> print s</div><div>First</div>
<div>>>> s = "Second"</div></blockquote><div><br></div></div></div><div>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.</div>
<div><br></div><div>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.</div><div><br></div><div>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".</div>
<div><br></div><div>If you try to modify the actual value of the string, you will raise an exception: </div><div><br></div><div><div>>>> s = "First"</div><div>>>> s[0] = "T"</div><div>
Traceback (most recent call last):</div><div> File "<stdin>", line 1, in <module></div><div>TypeError: 'str' object does not support item assignment</div></div><div><br></div><div>HTH,</div>
<div>Wayne</div></div>
</blockquote></div><div><br></div><div><br></div><div>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!</div>
<div><br></div><div><br></div><div><br></div><div>jM. </div><div><br></div><div><br></div>