Navigating through a string and updating the value of string while navigating
<p>I have got the following code in Python (in PyCharm Community Edition):</p>

<pre><code>def defer_tags(sentence):

    for letter in sentence:
        print(letter)
        if letter == '&lt;':
            end_tag = sentence.find('&gt;')
            sentence = sentence[end_tag+1:]
            print(sentence)

defer_tags("&lt;h1&gt;Hello")
</code></pre>

<p>It produced the following output:</p>

<pre class="lang-none prettyprint-override"><code>current letter =  &lt;
new_sentence =  Hello
current letter =  h
current letter =  1
current letter =  &gt;
current letter =  H
current letter =  e
current letter =  l
current letter =  l
current letter =  o
</code></pre>

<p>Why does loop (<code>letter</code>) navigate through the entire string (<code>sentence</code>) even though the value of <code>sentence</code> has changed inside the loop ?</p>

<p>I am printing out the value of <code>sentence</code> after the change but it is not getting reflected in the loop iterations.</p>

<p>To be explicit, try using beautiful soup following way:</p>

<pre><code>&gt;&gt;&gt; from BeautifulSoup import BeautifulSoup
&gt;&gt;&gt; soup = BeautifulSoup('&lt;h1&gt;Hello&lt;h1&gt;')
&gt;&gt;&gt; soup.text
u'Hello'
</code></pre>

python string for-loop