Remove the vowels from a string in Python
Understanding Vowel Removal
Vowel removal involves deleting all vowels (a, e, i, o, u) from a given string.
We will explore three different methods to remove vowels from a string using Python.
Method 1: Using a Loop
This method iterates through the string and constructs a new string without vowels.
def remove_vowels(s): result = "".join([c for c in s if c.lower() not in "aeiou"]) return result # Example usage s = "Hello World" print("String without vowels:", remove_vowels(s))
Output: String without vowels: Hll Wrld
Method 2: Using Recursion
This method removes vowels recursively.
def remove_vowels_recursive(s): if not s: return "" first = s[0] rest = remove_vowels_recursive(s[1:]) return first + rest if first.lower() not in "aeiou" else rest # Example usage s = "Programming" print("String without vowels:", remove_vowels_recursive(s))
Output: String without vowels: Prgrmmng
Method 3: Using Regular Expressions
This method uses regex to replace all vowels in the string.
import re def remove_vowels_regex(s): return re.sub(r"[aeiouAEIOU]", "", s) # Example usage s = "Count Vowels" print("String without vowels:", remove_vowels_regex(s))
Output: String without vowels: Cnt Vwls