
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to delete consonants from a string in Python?
The consonants are the alphabetic characters that is not a vowel (a, e, i, o, u). In Python, String manipulation is the common task, In this article we will explore how to delete consonants from a string using different approaches, including loops, list comprehensions and regular expression.
Using Loop
In this approach, we are going to declare the variable assignment with vowels in both upper and lower case and then looping through each character in the string. If the character is vowel or a non-alphabet character we will retrieve them and add to result.
Example
Let's look at the following example, where we are going to remove the consonants from the string "TutorialsPoint".
def demo(a): x = 'aeiouAEIOU' result = '' for char in a: if char in x or not char.isalpha(): result += char return result print(demo("TutorialsPoint"))
The output of the above program is as follows -
uoiaoi
Using List Comprehension
The second approach is by using the Python list comprehension, Where it is used to filter the characters and selects only the vowels and non-alphabetic characters. Then we will combine all those characters to form the single string using the join() method.
Example
In the following example, we are going to use the list comprehension and removing the consonants from the string.
def demo(text): x = 'aeiouAEIOU' return ''.join([char for char in text if char in x or not char.isalpha()]) print(demo("Welcome to TP."))
The following is the output of the above program -
eoe o .
Using Regular Expression
In this approach, we are going to use the Python regular expression, Here we are using the regex pattern '(?i)[b-df-hj-np-tv-z]' to match all the consonants regardless of case and manipulating all the consonants with empty string using the Python re.sub() method.
Example
Consider the following example, where we are going to remove the consonants from the string using the regular expression.
import re def demo(text): return re.sub(r'(?i)[b-df-hj-np-tv-z]', '', text) print(demo("Welcome"))
The following is the output of the above program -
eoe