Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python | Duplicate substring removal from list
Next article icon

Python – Remove all consonants from string

Last Updated : 11 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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)

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))
 
 
Output
The 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))
 
 
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
 
#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
 
 
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




# 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))
 
 
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:

  1. Initialize the string to be processed.
  2. 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.
  3. Use the filter() function with the lambda function and the string to create a filter object that contains only the vowels.
  4. 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))
 
 
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:

  1. Initialize the string to be processed.
  2. Use numpy to convert the string to a numpy array of integers, using the ‘fromstring’ method.
  3. Define a boolean mask to identify vowels, using the numpy ‘isin’ method.
  4. Use the boolean mask to filter the array to retain only vowels.
  5. 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).



Next Article
Python | Duplicate substring removal from list
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python string-programs
Practice Tags :
  • python

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
    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 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
  • Python | Remove Kth character from strings list
    Sometimes, while working with data, we can have a problem in which we need to remove a particular column, i.e the Kth character from string list. String are immutable, hence removal just means re creating a string without the Kth character. Let's discuss certain ways in which this task can be perfor
    7 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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences