Python – Remove all consonants from string
ometimes, 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.
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 stringtest_str = "Gfg is best for geeks"# printing original stringprint("The original string is : " + test_str)# Remove all consonants from string# Using loopres = []for chr in test_str: if chr in "aeiouAEIOU": res.extend(chr)res = "".join(res)# printing resultprint("String after consonants removal : " + str(res)) |
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 stringtest_str = "Gfg is best for geeks"# printing original stringprint("The original string is : " + test_str)# Remove all consonants from string# Using list comprehensionres = "".join([chr for chr in test_str if chr in "aeiouAEIOU"])# printing resultprint("String after consonants removal : " + str(res)) |



.png)