0

I'm going through some exercises in CodeAcademy. In one they ask you to write a function to remove all the vowels from a string. Apparently my function works with different texts, but it's not working with: "Hey look Words!". That's weird. Which could be my error? My code:

def anti_vowel(text):

    vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']

    letters = []
    for char in text:
        letters.append(char)
    for i in vowels:
        for j in letters:
            if i==j:
                letters.remove(j)

    new_text = ''.join(letters)
    print new_text
durron597
  • 31,968
  • 17
  • 99
  • 158
giulia_dnt
  • 197
  • 1
  • 4
  • 12
  • Does it tell you what the output and expected output are for "Hey look Words!"? – DanielGibbs Nov 16 '14 at 14:57
  • Should be the same string but with no vowels. With my function the output is "Hy lk Words!". So it fails to remove the last 'o'. – giulia_dnt Nov 16 '14 at 14:58
  • "y" is sometimes considered a vowel, too. Do your passing unit tests contain any "y"s? – Ulrich Schwarz Nov 16 '14 at 15:00
  • In the explanation they ask to not consider 'y' as a vowel. Anyway, I've tried several texts both with and without 'y's. Apparently I'm having trouble only with that specific string. – giulia_dnt Nov 16 '14 at 15:03

2 Answers2

1

Your problem is that you are modifying letters while iterating over it. Instead, try building a new list (and a few other changes):

no_vowels = []
for j in letters:
    if j not in vowels:
        no_vowels.append(j)

new_text = ''.join(no_vowels)
DanielGibbs
  • 9,910
  • 11
  • 76
  • 121
0

You can always do like this. You have to use another variable for new string.

>>> vowels = ['a','e','i','o','u', 'A', 'E', 'I', 'O', 'U']
>>> string = "Hey look Words!"
>>> new_string = ""
>>> for s in string:
    if s not in vowels:
        new_string += s


>>> print new_string
Hy lk Wrds!
Netro
  • 7,119
  • 6
  • 40
  • 58
  • Yes, other solutions for the assignment exist, such as `"".join((l for l in "Hey look words" if l not in 'aeiouAEIOU'))`, but that doesn't help the OP finding why their implementation doesn't work. – Ulrich Schwarz Nov 16 '14 at 15:04
  • Thank you all, I wasn't looking for other solutions, because at my learning stage it's better if I work with mine and just understand which are the mistakes I make. But thanks for all the tips! – giulia_dnt Nov 16 '14 at 15:13