Skip to content
Related Articles

Related Articles

Python – Remove all consonants from string

View Discussion
Improve Article
Save Article
  • Last Updated : 16 Sep, 2022
View Discussion
Improve Article
Save Article

Sometimes, while working with Python, we can have a problem in which we wish to remove all the non vowels from strings. This is quite popular question and solution to it is useful in competitive programming and day-day programming. Lets discuss certain ways in which this task can be performed.
Method #1 : Using loop 
This is one of the ways in which this task can be performed. In this, we iterate through the list and then check for non presence of vowels and filter.
 

Python3




# Python3 code to demonstrate working of
# Remove all consonants from string
# Using loop
 
# initializing string
test_str = "Gfg is best for geeks"
 
# printing original string
print("The original string is : " + test_str)
 
# Remove all consonants from string
# Using loop
res = []
for chr in test_str:
    if chr in "aeiouAEIOU":
        res.extend(chr)
res = "".join(res)
 
# printing result
print("String after consonants removal : " + str(res))

Output

The original string is : Gfg is best for geeks
String after consonants removal : ieoee

 
Method #2 : Using list comprehension 
This is one of the ways in which this task can be performed. In this, we iterate through the list and then filter out vowels in similar manner but in one-liner.
 

Python3




# Python3 code to demonstrate working of
# Remove all consonants from string
# Using list comprehension
 
# initializing string
test_str = "Gfg is best for geeks"
 
# printing original string
print("The original string is : " + test_str)
 
# Remove all consonants from string
# Using list comprehension
res = "".join([chr for chr in test_str if chr in "aeiouAEIOU"])
 
# printing result
print("String after consonants removal : " + str(res))

Output

The original string is : Gfg is best for geeks
String after consonants removal : ieoee

The Time and Space complexity for all methods are the same:

Time Complexity: O(n)

Space Complexity: O(n)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!