Anti_vowel


#1

hi,guys,what's wrong with my code?

def anti_vowel(text):
    s=list(text)
    for c in s:
        if c in "aeiouAEIOU":
            s.remove(c)
    return "".join(s)
print anti_vowel("Hey look Words!")

#2

If it is your code, then wouldn't you know where the error is, or how to find it? Sorry, I just have to call a spade a spade. I suspect it is returning,

Hy lok Words!

Got any ideas you want to explore?


#3

Thank you,but it turns out to be that return Hy lk,Words! And I still don't understand why the result is wrong.


#4

Right. I erred above because I just rattled it off. Not fair of me. Sorry.

Consider that list.remove() only removes one element.

loop cycles...

  1. remove e
  2. shift elements left; 'y' is in current iterator; gets skipped
  3. remove 'o'
  4. shift elements left; 'o' is in current iterator; gets skipped
  5. find 'o' in 'Words'
  6. remove 'o' in 'lok'

We can make the process simpler by not cycling through (iterating) the main object. The list of vowels is enough, since nothing else will be removed.

for vowel in "aeiouAEIOU":

But the real trick comes in how we get all the match instances.

    while vowel in s:
        s.remove(vowel)

Notice how the while conditional replaces the if statement?


#5

Thanks a lot.it's very helpful to me.