Skip to content
Advertisement

Remove the Last Vowel in Python

I have the following problem and I am wondering if there is a faster and cleaner implementation of the removeLastChar() function. Specifically, if one can already remove the last vowel without having to find the corresponding index first.

PROBLEM

Write a function that removes the last vowel in each word in a sentence.

Examples:

removeLastVowel("Those who dare to fail miserably can achieve greatly.")

“Thos wh dar t fal miserbly cn achiev gretly.”

removeLastVowel("Love is a serious mental disease.")

“Lov s serios mentl diseas”

removeLastVowel("Get busy living or get busy dying.")

“Gt bsy livng r gt bsy dyng”

Notes: Vowels are: a, e, i, o, u (both upper and lowercase).

MY SOLUTION

A PSEUDOCODE

  1. Decompose the sentence
  2. For each word find the index of the last vowel
  3. Then remove it and make the new “word”
  4. Concatenate all the words

CODE

def findLastVowel(word):
    set_of_vowels = {'a','e','i','o','u'}
    last_vowel=''
    for letter in reversed(word):
        if letter in set_of_vowels:
            last_vowel = letter
            break
    return last_vowel
 
def removeLastChar(input_str,char_to_remove):
    index = input_str.find(char_to_remove)
    indices = []
    tmp_str = input_str
    if index != -1:
        while index != -1:
            indices.append(index)
            substr1 = tmp_str[:index]
            substr2 = tmp_str[index+1:]
            tmp_str = substr1+"#"+substr2
            index = tmp_str.find(char_to_remove) 
        
        index = indices[-1]
        substr1 = input_str[:index]
        substr2 = input_str[index+1:]
        return (substr1+substr2)
    else:
        return (input_str)

def removeLastVowel(sentence):
    decomposed_sentence = sentence.split()
    out = []
    for word in decomposed_sentence:
        out.append(removeLastChar(word,findLastVowel(word)))
    print(" ".join(out))


#MAIN
removeLastVowel("Those who dare to fail miserably can achieve greatly.")
removeLastVowel("Love is a serious mental disease.")
removeLastVowel("Get busy living or get busy dying.")

OUTPUT

Thos wh dar t fal miserbly cn achiev gretly.
Lov s  serios mentl diseas.
Gt bsy livng r gt bsy dyng.

QUESTION

Can you suggest a better implementation of the removeLastChar() function? Specifically, if one can already remove the last vowel without having to find the corresponding index first.

Advertisement

Answer

This can be more easily achieved with a regex substitution that removes a vowel that’s followed by zero or more consonants up to a word boundary:

import re

def removeLastVowel(s):
    return re.sub(r'[aeiou](?=[^Waeiou]*b)', '', s, flags=re.I)

so that:

removeLastVowel("Those who dare to fail miserably can achieve greatly.")

returns:

Thos wh dar t fal miserbly cn achiev gretly.
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement