Home »
Python
Remove all consonants from the given string by using the re module in Python
Python re module example: Here, we are going to learn how to remove all consonants from the given string using Python programming language?
Submitted by Bipin Kumar, on November 01, 2019
To solve this type of problem, we will use the re module or regular expression module in the Python. Here, we will assume a string given by the user from which we have to remove all consonants that is we have to find all vowels present in the given strings. So, before going to solve this problem we will learn a little bit about re module.
What is re module in the Python?
Python has an inbuilt module called re which allows us to solve the various problems based on pattern matching and string manipulation.
Let us assume a string s is given by the user it has a mixture of consonants and vowels. Here, we are going to write Python code that will remove all consonants from the string s.
s = 'Includehelp is specially designed to provide help to students, working professionals and job seekers. We are fully dedicated to making each tutorial very simple to learn and understand.'
Code:
# importing the module
import re
# string initialization
s ='Includehelp is specially designed to provide help to students, working professionals and job seekers. We are fully dedicated to making each tutorial very simple to learn and understand.'
# removing all constants
s1=re.sub('[^aeiouAEIOU ]+','',s)
# printing the string after removing all constants
print(s1)
Output
Iuee i eia eie o oie e o ue oi oeioa a o eee e ae u eiae o ai ea uoia e ie o ea a uea
Explanation:
- Here, we have included the re module in the Python code by using the import function.
- In re module, re.sub use to replace the substring. The syntax of re.sub() is re.sub(Pattern, replace, string) and in the above code, we are replacing all letters with '' (empty space) excepting the vowel "aeiouAEIOU".
- At the end of the program, we are printing the left string after the replacement of all consonants and this is our requirement.