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>Without clearly knowing the intentions of your function and what you are attempting to do. I have an alternative to the answer that zvone gave.</p>

<p>This option is to remove any characters that you have not defined in an allowed characters list:</p>

<pre><code>characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ "

test_string = "This is an example!"

test_string = ''.join(list(filter(lambda x: x in characters, test_string)))

print(test_string)
</code></pre>

<p>This outputs:</p>

<blockquote>
  <p>This is an example</p>
</blockquote>

<p>Note, this is the Python 3 version.</p>

<p>Python 2, you do not need the <code>''.join(list())</code></p>

<p>Doing it this way would allow you to define any character that you do not want present in your string, and it will remove them. </p>

<p>You can even do the reverse:</p>

<pre><code>ignore_characters= "!"

test_string = "This is an example!"

test_string = ''.join(list(filter(lambda x: x not in ignore_characters, test_string)))

print(test_string)
</code></pre>

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