Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to delete consonants from a string in Python?
The consonants are the alphabetic characters that are not vowels (a, e, i, o, u). In Python, string manipulation is a common task. In this article, we will explore how to delete consonants from a string using different approaches, including loops, list comprehensions and regular expressions.
Using Loop
In this approach, we declare a variable containing vowels in both upper and lower case, then loop through each character in the string. If the character is a vowel or a non-alphabet character, we add it to the result ?
Example
Let's look at the following example, where we remove consonants from the string "TutorialsPoint" ?
def remove_consonants(text):
vowels = 'aeiouAEIOU'
result = ''
for char in text:
if char in vowels or not char.isalpha():
result += char
return result
print(remove_consonants("TutorialsPoint"))
The output of the above program is as follows −
uoiaoi
Using List Comprehension
The second approach uses Python list comprehension to filter characters and select only vowels and non-alphabetic characters. We then combine all those characters to form a single string using the join() method ?
Example
In the following example, we use list comprehension to remove consonants from the string ?
def remove_consonants(text):
vowels = 'aeiouAEIOU'
return ''.join([char for char in text if char in vowels or not char.isalpha()])
print(remove_consonants("Welcome to TP."))
The following is the output of the above program −
eoe o .
Using Regular Expression
In this approach, we use Python regular expressions. Here we use the regex pattern '(?i)[b-df-hj-np-tv-z]' to match all consonants regardless of case and replace all consonants with empty string using the Python re.sub() method ?
Example
Consider the following example, where we remove consonants from the string using regular expression ?
import re
def remove_consonants(text):
return re.sub(r'(?i)[b-df-hj-np-tv-z]', '', text)
print(remove_consonants("Welcome"))
print(remove_consonants("Python Programming"))
The following is the output of the above program −
eoe yo oai
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| Loop | Good | Medium | Simple understanding |
| List Comprehension | Excellent | Good | Pythonic approach |
| Regular Expression | Medium | Excellent | Complex patterns |
Conclusion
Use list comprehension for clean, readable code when removing consonants. Regular expressions are best for complex pattern matching, while loops provide the most straightforward approach for beginners.
