Replacing string element in for loop Python
<p>I am reading data in from a text file so each row is a list of strings, and all those lists are in a data list. So my lists look like:</p>

<pre><code>data = [row1, row2, etc.]
row1 = [str1, str2, etc.]
</code></pre>

<p>I am trying to remove any $ or % signs that appear in the strings in a row list. I have checked that if I try and do this for one individual element, say the second row and the fourth element has a "%", so:</p>

<pre><code>data[1][3] = data[1][3].replace("%","")
</code></pre>

<p>This will properly remove it, but when I try and use a nested for loop to do it all:</p>

<pre><code>for row in data:
    for x in row:
        x = x.replace("%","")
        x = x.replace("$","")
</code></pre>

<p>This doesn't remove any of the % or $ signs, I have tried just doing it without the second replace to see if it would at least remove the % signs, but even that didn't work.</p>

<p>Any ideas why this wouldn't work, or how I could do this?<br>
Thanks in advance for any help!</p>

<p>The problem is that your <em>str</em> variable is shadowing the builtin Python <a href="https://docs.python.org/2.7/library/functions.html#str" rel="nofollow"><em>str</em></a> variable.  That fix is easy.  Just use another variable name.</p>

<p>The second problem is that the replaced string isn't being replaced in the row list itself.  The fix is to save the replaced string back into the <em>row</em> list.  For that, you can use <a href="https://docs.python.org/2.7/library/functions.html#enumerate" rel="nofollow"><em>enumerate()</em></a> to give you both the value and its position in the row:</p>

<pre><code>for row in data:
    for i, x in enumerate(row):
        x = x.replace("%","")
        x = x.replace("$","")
        row[i] = x
</code></pre>

python python-2.7