How to Remove Vowels with Python

The challenge

Create a function called shortcut to remove all the lowercase vowels in a given string.


shortcut("codewars") # --> cdwrs
shortcut("goodbye")  # --> gdby

Don’t worry about uppercase vowels.

Test cases

import random

for t in [
  ["how are you today?","hw r y tdy?"],
    ans,exp = shortcut(t[0]), t[1]

Test.describe("Not so easy")
for t in [
  ["a e i o u, borriquito como tu","    , brrqt cm t","Isolated vowels let spaces between them"],
  ["Explicit is better than implicit", "Explct s bttr thn mplct","Should remove only lowercase vowel"],
  ["Beautiful is better than Ugly", "Btfl s bttr thn Ugly","Should remove only lowercase vowel"]
    ans,exp = shortcut(t[0]), t[1]

for t in random.sample([
  ["We are the Knights who say ni!","W r th Knghts wh sy n!"],
  ["Nobody expects the Spanish Inquisition!","Nbdy xpcts th Spnsh Inqstn!"],
  ["He's not the messiah. He's a very naughty boy!","H's nt th mssh. H's  vry nghty by!"],
  ["It's just a flesh wound.","It's jst  flsh wnd."],
  ["You don't frighten us, English pig dogs.","Y dn't frghtn s, Englsh pg dgs."],
  ["Mate, this parrot wouldn't VOOM if you put four million volts through it!","Mt, ths prrt wldn't VOOM f y pt fr mlln vlts thrgh t!"],
  ["Five is a sufficiently close approximation to infinity.","Fv s  sffcntly cls pprxmtn t nfnty."]
    ans,exp = shortcut(t[0]), t[1]

The solution in Python

Option 1 (long way):

def shortcut( s ):
    vowels = ('a', 'e', 'i', 'o', 'u')
    ss = ""
    for c in s:
        if c not in vowels:
            ss += c
    return ss

Option 2 (using translate):

def shortcut(s):
    return s.translate(None, 'aeiou')

Option 3 (using join):

def shortcut(s):
    return ''.join(c for c in s if c not in 'aeiou')

Option 4 (using lambda):

import re
shortcut = lambda s: re.sub('[aeiou]', '', s)

Option 5 (using replace):

def shortcut(s):
    for i in ["a","e","i","o","u"]:
        if i in s:
            s = s.replace(i,"")

Notify of
Inline Feedbacks
View all comments