Help me refactor my Anti-Vowel code


#1



Hi Everyone,

I was able to get my code to work by iterating through a string and assigning each letter to a separate list index and then iterating through the list to see if it matches the condition of one of the vowels. The code however seems very rough, does anyone have recommendations on refactoring?


def anti_vowel(text):
    tlist = []
    # append each letter in the list
    for i in text:
        tlist.append(i)
    # check if the letter in the list position is a vowel    
    for x in range(len(tlist)):
        if tlist[x] == 'a' or tlist[x] == 'A':
            tlist[x] = ''
        elif tlist[x] == 'e' or tlist[x] == 'E':
            tlist[x] = ''
        elif tlist[x] == 'i' or tlist[x] == 'I':
            tlist[x] = ''
        elif tlist[x] == 'o' or tlist[x] == 'O':
            tlist[x] = ''
        elif tlist[x] == 'u' or tlist[x] == 'U':
            tlist[x] = ''
        else:
            pass
        
    newlist = ''.join(tlist)
    print newlist
    return newlist


#2

Hey, here's a couple of solutions. Luckily python has us covered and makes it really easy to search if a string contains something.

def anti_vowel_alt(text):
    tlist = []
    for char in text:
        if char.lower() not in 'aeiou':
            tlist.append(char)
    return ''.join(tlist)

def anti_vowel_shortest(text):
    return ''.join(char for char in text if char.lower() not in 'aeiou')
 
print anti_vowel_alt("Hi there my name angusbeef")

#3

Please understand if x == ‘a’ or x == ‘A’ can be shortened to if x.lower() == ‘a’

Also, while looping, you can see if a character is in a string of characters or text, like so:

if char.lower() in ‘aeiou’:
    # do something

Based on the above, your function block can be:

no_vowels = ''

for char in text:
    if char.lower() not in 'aeiou':
        no_vowels += char

return no_vowels

If you know list comprehensions, this is another possibility:

vowels = 'aeiou'
no_vowels = [char for char in text if char.lower() not in vowels]

return ''.join(no_vowels)

#4

Wow. Thanks a lot for this. Love how it appends all characters other than vowels to the list.

The second function blew my mind. For the .join method, is that entire thing treated as an argument for the method?


#5

Ah thanks for this. I was trying to understand angusbeef's second function up there and you just told me what he did there (list comprehensions).

Thanks!


#6

Glad I could help :slight_smile:


#7

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