A better way to solve anti_vowel


Hey, guys! I'm currently in the "Practice Makes Perfect", and I've completed the part 8, "anti_vowel", but I think there's a better way to do it. Do you guys mind helping me figure it out? Thanks! My code is right below

def anti_vowel(text):
    vowels = ['a', 'e', 'i', 'o', 'u', 'A','E', 'I', 'O', 'U']
    n_text = ""
    for char in text:
        if char not in vowels:
            n_text = n_text + char
    return n_text


simple things you could change would be the vowels variable. it could just be a string like this: 'aeiuoAEIOU' and your code would work the same.
There are other methods to do this as well, but the lesson wanted you to do it the hard way.
There is already a string method called translate that does this exact thing.

The second post talks about this.
Translate is something that allows you to specify the translation table (used for replacements) as well as any characters which should be deleted in the process.
So the code:

def anti_vowel(string):
    return string.translate(None, 'aeiuoAEIOU')

is equivalent to what you did.


Thank you very much!


also, just to add, you could use .lower() method in if statement, convert 'char' to lowercase and have only 'a', 'e', 'i', 'o', 'u' in 'vowels' list.

it's better to modify what you want to evaluate than to have a container with all variations of data, because if the task was the oposite - to remove all consonants, would you add all B, C, D, F, G, H, J, K, L, M, N, P, Q, R, S, T, V, X, Z and b,c,d,f,g,h etc..? :slight_smile:

using lower() you change the character to lower case so you can match it with vowels list. note that doesn't change the "char" that you later pass to n_text. it's fine for this case where we have 10 characters, but just so you know for future, where you could have many varitations. always try to automate stuff, and avoid manual typing whenever possible.


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