Python - Remove all consonants from string
Last Updated :
11 May, 2023
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))
OutputThe 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))
OutputThe 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)
Method #3 : Using replace() method
There is one more way, while iterating through the string if consonant occur the we will replace that char with empty char.
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
vow = "aeiouAEIOU"
res = ""
# Using loop
for i in test_str:
if i not in vow:
test_str = test_str.replace(i, "")
# printing result
print("String after consonants removal : " + str(test_str))
OutputThe original string is : Gfg is best for geeks
String after consonants removal : ieoee
Method #4 : Using operator.countOf() method
Python3
# Python3 code to demonstrate working of
# Remove all consonants from string
# Using loop
import operator as op
# initializing string
test_str = "Gfg is best for geeks"
# printing original string
print("The original string is : " + test_str)
vowels = "aeiouAEIOU"
# Remove all consonants from string
# Using loop
res = []
for chr in test_str:
if op.countOf(vowels, chr) > 0:
res.extend(chr)
res = "".join(res)
# printing result
print("String after consonants removal : " + str(res))
OutputThe original string is : Gfg is best for geeks
String after consonants removal : ieoee
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #5 : Using re module (regular expressions)
Python3
import re
#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 regular expressions
res = re.sub(r'[^aeiouAEIOU]+', '', test_str)
#printing result
print("String after sentants removal : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy
OutputThe original string is : Gfg is best for geeks
String after sentants removal : ieoee
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #6 : Using ord()+for loop
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 = ""
vow=[97, 101, 105, 111, 117]
for chr in test_str:
if ord(chr) in vow:
res+=chr
# printing result
print("String after consonants removal : " + str(res))
OutputThe original string is : Gfg is best for geeks
String after consonants removal : ieoee
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #7: Using filter() and lambda function
In this method, we can use the built-in filter() function with a lambda function to filter out all the consonants in the string.
Step-by-step approach:
- Initialize the string to be processed.
- Define a lambda function that will filter out all the consonants from the string. The lambda function should take one argument (a character), and it should return True if the character is a vowel and False otherwise.
- Use the filter() function with the lambda function and the string to create a filter object that contains only the vowels.
- Convert the filter object to a string using the join() method to get the final output string.
Python3
# Python3 code to demonstrate working of
# Remove all consonants from string
# Using filter() and lambda function
# 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 filter() and lambda function
res = ''.join(filter(lambda x: x in 'aeiouAEIOU', test_str))
# printing result
print("String after consonants removal : " + str(res))
OutputThe original string is : Gfg is best for geeks
String after consonants removal : ieoee
Time complexity: O(n)
Auxiliary space: O(n)
Method #8: Using numpy:
Algorithm:
- Initialize the string to be processed.
- Use numpy to convert the string to a numpy array of integers, using the 'fromstring' method.
- Define a boolean mask to identify vowels, using the numpy 'isin' method.
- Use the boolean mask to filter the array to retain only vowels.
- Use numpy 'chararray' method to convert the numpy array back to a string.
Python3
import numpy as np
# initializing string
test_str = "Gfg is best for geeks"
# printing original string
print("The original string is : " + test_str)
# convert the string to an array of Unicode code points
arr = np.array([ord(c) for c in test_str])
# select only the vowels (Unicode code points)
vowels = np.array([97, 101, 105, 111, 117])
res_arr = arr[np.isin(arr, vowels)]
# convert the array of Unicode code points back to a string
res = "".join([chr(c) for c in res_arr])
# printing result
print("String after consonants removal : " + str(res))
#This code is contributed by Pushpa.
Output:
The original string is : Gfg is best for geeks
String after consonants removal : ieoee
Time Complexity:
The code involves creating two NumPy arrays, which takes O(n) time, where n is the length of the input string.
The operation of selecting only the vowels involves a comparison between two arrays, which takes O(n) time as well.
The final step of converting the array back to a string takes O(n) time too.
Therefore, the total time complexity of the code is O(n).
Space Complexity:
The code creates two NumPy arrays, which take O(n) space, where n is the length of the input string.
There are no other significant memory allocations in the code.
Therefore, the total space complexity of the code is also O(n).
Similar Reads
Python | Remove all digits from a list of strings The problem is about removing all numeric digits from each string in a given list of strings. We are provided with a list where each element is a string and the task is to remove any digits (0-9) from each string, leaving only the non-digit characters. In this article, we'll explore multiple methods
4 min read
Remove Multiple Characters from a String in Python Removing multiple characters from a string in Python can be achieved using various methods, such as str.replace(), regular expressions, or list comprehensions. Each method serves a specific use case, and the choice depends on your requirements. Letâs explore the different ways to achieve this in det
2 min read
Remove spaces from a string in Python Removing spaces from a string is a common task in Python that can be solved in multiple ways. For example, if we have a string like " g f g ", we might want the output to be "gfg" by removing all the spaces. Let's look at different methods to do so:Using replace() methodTo remove all spaces from a s
2 min read
Remove Special Characters from String in Python When working with text data in Python, it's common to encounter strings containing unwanted special characters such as punctuation, symbols or other non-alphanumeric elements. For example, given the input "Data!@Science#Rocks123", the desired output is "DataScienceRocks123". Let's explore different
2 min read
Python - Remove Punctuation from String In this article, we will explore various methods to Remove Punctuations from a string.Using str.translate() with str.maketrans()str.translate() method combined with is str.maketrans() one of the fastest ways to remove punctuation from a string because it works directly with string translation tables
2 min read
Recursively Count Vowels From a String in Python Python is a versatile and powerful programming language that provides various methods to manipulate strings. Counting the number of vowels in a string is a common task in text processing. In this article, we will explore how to count vowels from a string in Python using a recursive method. Recursion
3 min read
Python - Remove Rear K characters from String List Sometimes, we come across an issue in which we require to delete the last characters from each string, that we might have added by mistake and we need to extend this to the whole list. This type of utility is common in web development. Having shorthands to perform this particular job is always a plu
5 min read
Python Program To Remove all control characters In the telecommunication and computer domain, control characters are non-printable characters which are a part of the character set. These do not represent any written symbol. They are used in signaling to cause certain effects other than adding symbols to text. Removing these control characters is
3 min read
How to Remove a Substring in Python? In Python, removing a substring from a string can be achieved through various methods such as using replace() function, slicing, or regular expressions. Depending on your specific use case, you may want to remove all instances of a substring or just the first occurrence. Letâs explore different ways
2 min read
Python | Remove given character from Strings list Sometimes, while working with Python list, we can have a problem in which we need to remove a particular character from each string from list. This kind of application can come in many domains. Let's discuss certain ways to solve this problem. Method #1 : Using replace() + enumerate() + loop This is
8 min read