This is my first experience with Python. I'm following an exercise out of the Head First Python book. I'm trying to convert one string into another string. (Changing "Don't panic!" into "on tap".) First, I convert the string into a list. Then, I use an if statement in a for loop to filter out the letters that I don't need.
I'm getting some very strange behavior, though! Here's my code:
phrase = "Don't panic!"
plist = list(phrase)
print(phrase)
print(plist)
for character in plist:
if character not in ['o', 'n', 't', 'a', 'p', ' ']:
plist.remove(character)
print("removing ", character)
new_phrase = ''.join(plist)
print(plist)
print(new_phrase)
And here's my output:
Don't panic!
['D', 'o', 'n', "'", 't', ' ', 'p', 'a', 'n', 'i', 'c', '!']
removing D
removing '
removing i
removing !
['o', 'n', 't', ' ', 'p', 'a', 'n', 'c']
ont panc
Why is the letter "c" still there? It's not in the array that I used in the if statement, and the rest of the characters get filtered out. But not the "c". Why?