8.Anti_vowel


#1




I tired to complete this excercise using replace method in Python. But code generates wrong output.
Error:
Your function fails on anti_vowel("Hey look Words!"). It returns "Hey lk Wrds!" when it should return "Hy lk Wrds!".


Whats wrong with my code?

def anti_vowel(text):
    new = text
    for i in range(len(text)):
        if text[i] in "aeiouAEIOU":
            new = text.translate(None, text[i])
    return new

#2

using build in functions like translate can be tricky, maybe read on how to use translation:

python doc -translation

look:

print "abcdefgabcdefgabcdefg".translate(None,'a')

this simply remove all cases of a

but in python, strings are immutable. we can see this beautiful when adding a print statement to your code:

def anti_vowel(text):
    new = text
    for i in range(len(text)):
        if text[i] in "aeiouAEIOU":
            new = text.translate(None, text[i])
            print new
    return new
print anti_vowel("hey look words")

see? first e gets removed. but then when a o is encountered, the original string is translated again


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.