<br><br><div class="gmail_quote">On Mon, Oct 24, 2011 at 1:52 PM, Wayne Werner <span dir="ltr">&lt;<a href="mailto:waynejwerner@gmail.com">waynejwerner@gmail.com</a>&gt;</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">&lt;<a href="mailto:jmartiee@gmail.com" target="_blank">jmartiee@gmail.com</a>&gt;</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>&lt;code&gt; </div><div><br></div><div>&gt;&gt;&gt; s = &quot;First&quot;</div><div>&gt;&gt;&gt; print s.__class__</div><div>&lt;type &#39;str&#39;&gt;</div><div>&gt;&gt;&gt; print s</div><div>First</div>



<div>&gt;&gt;&gt; s = &quot;Second&quot;</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 = &quot;First&quot; then you are telling python that you want to be able to refer to the string &quot;First&quot; by the name/variable s.</div><div><br></div><div>When you execute s=&quot;Second&quot; you are now telling python that instead of referring to &quot;First&quot; you want the name &#39;s&#39; to refer to the string &quot;Second&quot;.</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>&gt;&gt;&gt; s = &quot;First&quot;</div><div>&gt;&gt;&gt; s[0] = &quot;T&quot;</div><div>


Traceback (most recent call last):</div><div>  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;</div><div>TypeError: &#39;str&#39; 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>