- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
- Python Advanced Tutorial
- Python - Classes/Objects
- Python - Reg Expressions
- Python - CGI Programming
- Python - Database Access
- Python - Networking
- Python - Sending Email
- Python - Multithreading
- Python - XML Processing
- Python - GUI Programming
- Python - Further Extensions
How to delete consonants from a string in Python?
It is easiest to use regular expressions for this problem. You can separate multiple characters by "|" and use the re.sub(chars_to_replace, string_to_replace_with, str). We have For example:
>>> import re >>> consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z'] >>> re.sub('|'.join(consonants), "", "Hello people", flags=re.IGNORECASE) "eo eoe"
Note: You can also use the  to create group of characters to replace in regex.
If you want to keep only vowels and remove all other characters, you can use an easier version. Note that it'll remove spaces, numbers, etc. as well. For example,
>>> import re >>> re.sub('[^aeiou]', "", "Hello people", flags=re.IGNORECASE) "eoeoe"
You can also filter out the consonants as follows:
>>> consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z'] >>> s = "Hello people" >>> ''.join(c for c in s if c.lower() not in consonants) 'eo eoe'
- Related Articles
- How to delete a character from a string using python?
- How to remove consonants from a string using regular expressions in Java?
- How to find consonants in a given string using Java?
- How to delete lines from a Python tkinter canvas?
- How to detect vowels vs consonants in Python?
- Python Pandas - How to delete a row from a DataFrame
- Check if a string can be converted to another string by replacing vowels and consonants in Python
- How to Delete Specific Line from a Text File in Python?
- Delete all whitespaces from a String in Java
- How to delete the vowels from a given string using C language?
- How to count number of vowels and consonants in a string in C Language?
- Java program to delete duplicate characters from a given String
- How to Remove Punctuations From a String in Python?
- How to extract numbers from a string in Python?