HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMajor

Remove all vowels from a string except an initial character

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
vowelsallcharacterremoveinitialexceptfromstring

Problem

I've written the following code where all vowels are removed from a string except if the string starts with a vowel then this vowel is maintained.

def removeVowels(string):
    output = string[0]

    for char in string[1:]:
        if char.lower() not in 'aeuio':
            output += char
    return output


I was wondering if it's possible to use a list comprehension for this?

Solution

removeVowels is not quite an accurate name. Furthermore, by PEP 8, the official Python style guide, function names should be lower_case_with_underscores unless you have a good reason to deviate. Therefore, I recommend renaming the function to remove_non_initial_vowels.

Your function crashes on string[0] if the input is an empty string.

I don't recommend writing string[1:], since that would entail making a temporary copy of nearly the entire string.

'aeuio' is a bit weird. Why not 'aeiou'? (I assume that for this exercise, you don't care that y is sometimes a vowel, w is a semivowel, and assume that the string contains no diacritics.)

Fundamentally, this operation is a fancy string substitution. Typically, such substitutions are best done using regular expressions.

import re

def remove_non_initial_vowels(string):
    return re.sub('(?<!^)[aeiou]', '', string, flags=re.I)


The (?<!^) part of the expression is a negative lookbehind assertion that means "not at the beginning of the string".

Code Snippets

import re

def remove_non_initial_vowels(string):
    return re.sub('(?<!^)[aeiou]', '', string, flags=re.I)

Context

StackExchange Code Review Q#151716, answer score: 29

Revisions (0)

No revisions yet.