a mistake I keep having with for loops and return statements
<p>I have been noticing a problem I am having whenever I try to make a function that takes changes a string or a list then returns it. </p>

<p>I will give you an example of this happening with a code I just wrote:</p>

<pre><code>def remove_exclamation(string):
string.split(' ')
for i in string:
    i.split()
    for char in i:
        if char == '!':
            del char
            ''.join(i)
            ' '.join(string)
return string
</code></pre>

<p>For instance, I create this code to take a string as its parameter, remove any exclamation in it, the return it changed. The input and output should look like this:</p>

<pre><code>&gt;&gt;&gt;remove_exclamation('This is an example!')
'This is an example'
</code></pre>

<p>But instead I get this:</p>

<pre><code>&gt;&gt;&gt;remove_exclamation('This is an example!')
'This is an example!'
</code></pre>

<p>The function is not removing the exclamation in the output, and is not doing what I intended for it to day.</p>

<p>How can I keep avoiding this when I make for loops, nested for loops etc?</p>

<p>Strings are immutable in Python. And you cannot change them. You can however, re-assign there values.</p>

<p>That is where your problem lies. You never reassign the value of your strings, when you call <code>.split()</code> on them. </p>

<p>But there are also others errors in your program such as:</p>

<ul>
<li>Your indention</li>
<li>The fact that your just returning the string thats passed into the function</li>
<li>Your use of the <code>del</code> statement</li>
<li>etc.</li>
</ul>

<p>Instead, create a new string by iterating through the old one and filtering out the character(s) you do not want, via list comprehension and <code>''.join()</code>.</p>

<pre><code>def remove_exclamation(string):
    return ''.join([char for char in string if char != '!'])
</code></pre>

<p>But as @Moses has already said in the comments, why not just use <code>str.replace()</code>?:</p>

<p><code>string = string.replace('!', '')</code></p>

python python-3.x for-loop return return-value