Placement Prep

Remove Vowels from a String in Python: 4 Methods

Four Python methods to remove vowels from a string: for loop, list comprehension, filter(), and regex. With time complexity and placement coding round patterns.

By FACE Prep Team 4 min read
python string-manipulation placement-prep coding-interview technical-python

Removing vowels from a string is a classic string-filtering problem in Python: four approaches cover it, from the for-loop beginners start with to the regex one-liner used in production text preprocessing.

The problem: given a string, return a new string containing only the non-vowel characters in their original order. Vowels are a, e, i, o, u in both uppercase and lowercase.

Problem Statement

Input: A string s of any length, containing letters, digits, or special characters.

Output: A new string with all vowels removed and all other characters preserved.

InputOutputNotes
"FACEPREP""FCPRP"Uppercase vowels removed
"hello""hll"Lowercase vowels removed
"rhythm""rhythm"No vowels, string unchanged
"aeiou"""All vowels, empty string returned
"abc123""bc123"Digits kept, only the vowel removed
"ha ha""h h"Spaces are not vowels

The original WP version of this problem used only uppercase input. Placement tests send mixed-case strings, so the correct implementation handles both with a single vowel set: "aeiouAEIOU".

Method 1: For Loop

The most explicit approach. Iterate over each character and keep it only if it is not a vowel.

def remove_vowels_loop(s):
    vowels = "aeiouAEIOU"
    result = ""
    for char in s:
        if char not in vowels:
            result += char
    return result

# Test cases
print(remove_vowels_loop("FACEPREP"))  # FCPRP
print(remove_vowels_loop("hello"))     # hll
print(remove_vowels_loop("aeiou"))     # (empty string)
print(remove_vowels_loop(""))          # (empty string)

This is readable and correct. One caveat: string concatenation (result += char) creates a new string object on each iteration, so the approach scales as O(n^2) for very long inputs due to repeated memory allocation. For placement test inputs, which are typically under a few thousand characters, the difference is not observable.

For more Python basic programs, the loop-filter-accumulate pattern here appears in dozens of classic exercises: counting vowels, extracting digits, filtering uppercase letters.

Method 2: List Comprehension and join()

The preferred Python idiom. Use a generator expression to produce each consonant, then call str.join() to assemble the result in one allocation:

def remove_vowels_comprehension(s):
    vowels = "aeiouAEIOU"
    return "".join(c for c in s if c not in vowels)

# One-liner form
print("".join(c for c in "FACEPREP" if c not in "aeiouAEIOU"))  # FCPRP
print("".join(c for c in "hello"    if c not in "aeiouAEIOU"))  # hll

The join() method makes a single pass over the generator and builds the result string in one allocation. No repeated concatenation, no intermediate list object stored. This runs in true O(n) time and is the form most Python interviewers expect to see.

Method 3: filter() Function

Python’s built-in filter() applies a function to each element of an iterable and keeps only the elements where the function returns True:

def remove_vowels_filter(s):
    vowels = "aeiouAEIOU"
    return "".join(filter(lambda c: c not in vowels, s))

# Test
print(remove_vowels_filter("hello"))     # hll
print(remove_vowels_filter("FACEPREP"))  # FCPRP

filter() returns a lazy iterator, so wrapping it with join() is necessary to get a string back. Functionally identical to the list comprehension method. When checking whether a given character is upper case, lower case, a number, or a special character, the same filter() and lambda approach applies to character classification problems.

Method 4: Regular Expression

For one-liner use and text preprocessing pipelines, re.sub() gives the most compact form:

import re

def remove_vowels_regex(s):
    return re.sub("[aeiouAEIOU]", "", s)

# With IGNORECASE flag (shorter character class)
def remove_vowels_regex_nocase(s):
    return re.sub("[aeiou]", "", s, flags=re.IGNORECASE)

print(remove_vowels_regex("FACEPREP"))           # FCPRP
print(remove_vowels_regex_nocase("Hello World")) # Hll Wrld

re.sub(pattern, repl, string) replaces every match of pattern with repl. The character class [aeiouAEIOU] matches any single vowel. Replacing each match with "" removes it. The re.IGNORECASE variant shortens the character class to lowercase only and produces identical output.

The tradeoff with regex: the regex engine has higher startup overhead than a generator expression, so for short strings the comprehension method runs faster. For very long strings, the regex engine gains back some of that through lower Python bytecode overhead per character.

Time and Space Complexity

MethodTimeSpaceBest Use
For loopO(n^2) worst-caseO(n)Readable starter code
List comprehensionO(n)O(n)Preferred Python idiom
filter()O(n)O(n)Functional programming style
re.sub()O(n)O(n)Text preprocessing pipelines

For a placement test answer: state O(n) time complexity and O(n) space (for the output string). If asked to justify, note that the list comprehension avoids repeated string concatenation and builds the result in a single join() allocation.

Edge Cases to Handle

Placement test variants introduce edge cases the basic solution must handle correctly:

  • Empty string: "" returns "". All four methods return an empty string without errors.
  • All vowels: "aeiou" returns "". Correct output is an empty string, not None.
  • No vowels: "rhythm" returns "rhythm". The string passes through unchanged.
  • Mixed case: "Hello" returns "Hll". Both 'e' and 'o' are removed regardless of case.
  • Digits and symbols: "h3ll0" returns "h3ll0". Non-alphabetic characters are not vowels.
  • Whitespace: "ha ha" returns "h h". Spaces are not vowels and are preserved.

Placement Test Patterns

This character-filtering problem appears in AMCAT, CoCubes, and campus technical rounds in several forms. The direct “remove vowels” variant is the most common, but knowing the underlying pattern prepares you for the variations:

  • Count vowels vs. consonants: instead of building a result string, maintain two counters that increment on each character.
  • Keep only vowels (remove consonants): flip the condition from not in vowels to in vowels.
  • Remove vowels from each word in a sentence: split on spaces with s.split(), apply the same filter to each word, then rejoin.
  • Alternating vowels and consonants in output: requires two passes: collect vowels into one list and consonants into another, then interleave.

All four variations use the same single-character iteration skeleton. Once you have understood sorting a string in alphabetical order as a character-level operation, the filtering pattern here becomes a predictable building block.

The filtering logic here (test each character, keep or discard it, join the survivors) is also exactly the pattern inside text preprocessing steps in LLM pipelines: tokenize, filter noise tokens, normalize the vocabulary, pass forward. TinkerLLM’s Python-first environment is where you can run that same logic against a real language model at ₹299; the Python skills you’re sharpening for placement coding tests map directly to what goes inside those pipelines.

Primary sources

Frequently asked questions

What is the time complexity of removing vowels from a string in Python?

All four approaches run in O(n) time where n is the string length. The list comprehension version is fastest in practice because it avoids repeated string concatenation overhead and builds the result in a single join() allocation.

How do I handle both uppercase and lowercase vowels in Python?

Include both cases in the vowel check string: vowels = 'aeiouAEIOU'. Alternatively, call s.lower() before checking, but that changes the output case, which is usually not what you want.

Can I remove vowels from a string in one line of Python?

Yes: result = ''.join(c for c in s if c not in 'aeiouAEIOU'). This is the list comprehension approach written as a single expression, and it is the form most interviewers expect.

What if the input string contains only vowels?

All four methods return an empty string, which is the correct output. Some problem variants ask for a message like 'No consonants found' instead of an empty string, so read the problem statement carefully.

Does this work for special characters and digits?

Yes. Non-alphabetic characters such as digits, spaces, and punctuation are not in the vowel set 'aeiouAEIOU', so they pass through unchanged in all four methods.

Why does re.sub use square brackets like [aeiouAEIOU]?

The square brackets in a regex define a character class. Any single character matching any character listed inside gets replaced. re.sub('[aeiouAEIOU]', '', s) replaces each vowel match with an empty string, removing it from the output.

Build AI projects

A self-paced playground for building with LLMs.

TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.

Try TinkerLLM (₹299 launch)
Free AI Roadmap PDF