Question:

Trolls are attacking your comment section! A common way to deal with this situation is to remove all of the vowels from the trolls’ comments, neutralizing the threat.

Your task is to write a function that takes a string and returns a new string with all vowels removed.

For example, the string “This website is for losers LOL!” would become “Ths wbst s fr lsrs LL!”.

Note: For this exercise, ‘y' isn’t considered a vowel.

Answer:

This doesn’t look too bad, does it? Let’s jump right in!

The first thing we notice is that we can use a Regular Expression (RegEx) to greatly reduce the complexity of the solution. Our goal is to replace every vowel (lower and uppercase) with a blank space. We can use the Regex expression’s ‘substitute‘ method to replace all the vowels with a blank space.

In python, RegEx uses the “re” class, so let’s be sure to import that in our code:

import re

def disemvowel(string_):
    vowelRegex = re.compile(r'[aeiouAEIOU]')
    ans = vowelRegex.sub("", string_)
    return ans

print(disemvowel("This website is for losers LOL!"))

>> Ths wbst s fr lsrs LL!

The code works! Let’s refactor the code to one line:

import re

def disemvowel(string_):
    return re.compile(r'[aeiouAEIOU]').sub("", string_)

print(disemvowel("This website is for losers LOL!"))

>> Ths wbst s fr lsrs LL!

RegEx expressions are incredibly powerful, but I’d venture to guess that most programmers do not utilize them. Learn, utilize, and master them – they really are an irreplaceable tool in your toolbox!

Leave a Reply

Your email address will not be published. Required fields are marked *