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
  • 2
    It's usually a bad idea to remove things from a list while iterating over it. Commented Jul 31, 2020 at 16:54

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks @Telmo Trooper, this somehow works. I wonder if it could be done without importing any module.
@RobleyOchieng Okay, I updated my answer to add an approach which does not require any import, similar to what you originally tried. If this answer helped you please upvote it. 😁️
Thanks @Telmo Trooper, the one you updated works better for me: Thanks a lot.
My upvote can't reflect yet as am new here. I will upvote it, it helped me
No problem. I believe you can "accept" the answer though.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.