Where is the error ? anti_vowel


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/1/2?curriculum_id=4f89dab3d788890003000096#

Oops, try again. Your function fails on anti_vowel("Yab Gab to Trab Yab Yab Aeiouz"). It returns "Yb Gb t Trb Yb Yb euz" when it should return "Yb Gb t Trb Yb Yb z".


Does anybody knows what is happening? What's the problem with the last word "Aeiouz" ?
Sorry for my english, I hope you understand me


def anti_vowel(text):
    letter=0
    while letter<=len(text)-1:
        if text[letter] in 'aeiou':
            text=text.replace(text[letter],"")
        elif text[letter] in 'AEIOU':
            text=text.replace(text[letter],"")
        else:
            pass
        letter+=1
    return text


#2

You're not accounting for that letters will move when you create shorter strings. Your index doesn't point at each letter one at a time, instead it increases by 1 each time which doesn't work out when things move.

Also note that this has absolutely no effect

else:
    pass

#3

Thank you very much ionatan! I changed and it worked now, for this case a "for" loop is better than a "while" one.


#4

Well, the difference is that with a for-loop you're only looping through the original string, whereas with your while you were looking at a new one each time. You were doing different things with them, they can still do the same things.

Something you should take note of here is that you are creating a lot of strings (each time you replace you copy the whole or almost the whole thing) so if you for example ran this on a whole book, then it would be faster to just do the job by hand due to the extreme amount of work this would be doing.

The replace function does quite a lot of work, it's meant to be used once, not once for each character in a string. So it's important to know what the things you use actually do so that you can write code that ends up executing a reasonable amount of work for the task at hand.

A more sensible approach would be to loop through the string once in total, same as how a human would do it.

Strings also cannot be changed, so this more sensible approach would need an intermediary data type that can be changed which can then be fed to the string constructor to create the final result. (Now it's actually looping through it twice and actually a few more times, but multiplying by a constant is fine, that's just saying there are multiple steps to do. Copy the whole thing once for each letter is much, much worse)


#5

Understood. Thanks for the help!