Don't call remove
on a list while iterating over it.
Think about what happens when you do it.
- First,
words = 'uURII'
, and i
is pointing at its first character.
- You call
words.remove(i)
. Now words = 'URII'
, and i
is pointing at its first character.
- Next time through the loop,
words = 'URII'
, and i
is pointing to its second character. Oops, you've missed the U
!
There are a few ways to fix this—you can iterate over a copy of the list, or you can index it from the end instead of the start, or you can use indices in a while
loop and make sure not to increment until you've found something you don't want to delete, etc.
But the simplest way is to just build up a new list:
def disemvowel(word):
words = list(word)
new_letters = []
for i in words:
if i.upper() == "A" or i.upper() == "E" or i.upper() == "I" or i.upper() == "O" or i.upper() == "U":
pass
else:
new_letters.append(i)
print(''.join(new_letters))
This means you no longer need list(word)
in the first place; you can just iterate over the original string.
And you can simplify this in a few other ways—use a set membership check instead of five separate ==
checks, turn the comparison around, and roll the loop up into a list comprehension (or a generator expression):
def disemvowel(word):
vowels = set('AEIOU')
new_letters = [letter for letter in word if letter.upper() not in vowels]
print(''.join(new_letters))
… but the basic idea is the same.