1

I am trying to remove vowel objects that are in word(word is a list of letters making the userWord). If the userWord starts with consonant, the code works okay(removes all the vowels), but if useWord starts with vowel, it doesn't remove the first vowel while I want to remove all the vowels in the useWord. Did I skip something? Apologies, am a beginner. I'm using Python 3.8.5

def voweleater(userWord):
    word = list(userWord)
    vowels = ['a', 'e', 'i', 'o', 'u']
    for letter in word:
        for i in vowels:
            if i in word:
                word.remove(i)
        print(letter)
voweleater("abstemious")

Code output:

a
s
t
m
s

1 Answers1

1

Regex approach (cleaner, likely better optimized)

from re import sub

def remove_vowels(word):
    return sub(r'[aeiouAEIOU]', "", word)

print(remove_vowels("abstemious")) # Returns "bstms"

Regular expression [aeiouAEIOU] matches any vowel without an accent, we then use re.sub to replace the matches found with an empty space.

Array splitting approach (more verbose, likely slower)

def remove_vowels(word):
    characters = list(word)
    vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']

    for index, letter in reversed(list(enumerate(characters))):
        if letter in vowels:
            characters.pop(index)
    
    return "".join(characters)

print(remove_vowels("abstemious")) # Returns "bstms"

This way you'll iterate through your characters in reverse (so you'll always remove values from the end, preventing you from accidentally trying to read an index that doesn't exist anymore). If the current letter is a vowel, you remove it. Then you return a string joining the remaining characters.

Telmo Trooper
  • 4,993
  • 1
  • 30
  • 35