How to Remove Vowels with Python

The challenge

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

Examples

shortcut("codewars") # --> cdwrs shortcut("goodbye") # --> gdby
Code language: Python (python)

Don’t worry about uppercase vowels.

Test cases

import random Test.describe("Easy") for t in [ ["hello","hll"], ["hellooooo","hll"], ["how are you today?","hw r y tdy?"], ["complain","cmpln"], ["never","nvr"] ]: ans,exp = shortcut(t[0]), t[1] Test.assert_equals(ans,exp) 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] Test.assert_equals(ans,exp) # 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."] ],7): ans,exp = shortcut(t[0]), t[1] Test.assert_equals(ans,exp)
Code language: Python (python)

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
Code language: Python (python)

Option 2 (using translate):

def shortcut(s): return s.translate(None, 'aeiou')
Code language: Python (python)

Option 3 (using join):

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

Option 4 (using lambda):

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

Option 5 (using replace):

def shortcut(s): for i in ["a","e","i","o","u"]: if i in s: s = s.replace(i,"") return(s)
Code language: Python (python)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments