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
test_str = "Gfg is best for geeks"
print ( "The original string is : " + test_str)
res = []
for chr in test_str:
if chr in "aeiouAEIOU" :
res.extend( chr )
res = "".join(res)
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
test_str = "Gfg is best for geeks"
print ( "The original string is : " + test_str)
res = " ".join([chr for chr in test_str if chr in " aeiouAEIOU"])
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)
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
test_str = "Gfg is best for geeks"
print ( "The original string is : " + test_str)
vow = "aeiouAEIOU"
res = ""
for i in test_str:
if i not in vow:
test_str = test_str.replace(i, "")
print ( "String after consonants removal : " + str (test_str))
|
Output
The original string is : Gfg is best for geeks
String after consonants removal : ieoee
Method #4 : Using operator.countOf() method
Python3
import operator as op
test_str = "Gfg is best for geeks"
print ( "The original string is : " + test_str)
vowels = "aeiouAEIOU"
res = []
for chr in test_str:
if op.countOf(vowels, chr ) > 0 :
res.extend( chr )
res = "".join(res)
print ( "String after consonants removal : " + str (res))
|
Output
The 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
test_str = "Gfg is best for geeks"
print ( "The original string is : " + test_str)
res = re.sub(r '[^aeiouAEIOU]+' , '', test_str)
print ( "String after sentants removal : " + str (res))
|
Output
The 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
test_str = "Gfg is best for geeks"
print ( "The original string is : " + test_str)
res = ""
vow = [ 97 , 101 , 105 , 111 , 117 ]
for chr in test_str:
if ord ( chr ) in vow:
res + = chr
print ( "String after consonants removal : " + str (res))
|
Output
The 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
test_str = "Gfg is best for geeks"
print ( "The original string is : " + test_str)
res = ' '.join(filter(lambda x: x in ' aeiouAEIOU', test_str))
print ( "String after consonants removal : " + str (res))
|
Output
The 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
test_str = "Gfg is best for geeks"
print ( "The original string is : " + test_str)
arr = np.array([ ord (c) for c in test_str])
vowels = np.array([ 97 , 101 , 105 , 111 , 117 ])
res_arr = arr[np.isin(arr, vowels)]
res = "".join([ chr (c) for c in res_arr])
print ( "String after consonants removal : " + str (res))
|
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
Python - Remove K length Duplicates from String
To remove consecutive K-length duplicates from a string iterate through the string comparing each substring with the next and excluding duplicates. For example we are given a string s = "abcabcabcabc" we need to remove k length duplicate from the string so that the output should become "aaaabc" . We
3 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
3 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
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 | Duplicate substring removal from list
Sometimes we can come to the problem in which we need to deal with certain strings in a list that are separated by some separator and we need to remove the duplicates in each of these kinds of strings. Simple shorthands to solve this kind of problem is always good to have. Let's discuss certain ways
7 min read
Python | Remove all strings from a list of tuples
Given a list of tuples, containing both integer and strings, the task is to remove all strings from list of tuples. Examples: Input : [(1, 'Paras'), (2, 'Jain'), (3, 'GFG'), (4, 'Cyware')] Output : [(1), (2), (3), (4)] Input : [('string', 'Geeks'), (2, 225), (3, '111')] Output : [(), (2, 225), (3,)]
8 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 table
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