To remove vowels from a string in Python, the easiest way is to use a regular expression search.

import re

string_example = "This is a string with some vowels and other words."

string_without_vowels = re.sub("[aeiouAEIOU]","",string_example)

print(string_without_vowels)

#Output:
Ths s  strng wth sm vwls nd thr wrds.

You can also use a loop which will loop over all characters in your string and remove all of the vowels.

def removeVowels(str):
    new_str = ""
    for char in str:    
        if char not in ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'):
            new_str = new_str + char
    return new_str

string_example = "This is a string with some vowels and other words."

print(removeVowels(string_example))

#Output:
Ths s  strng wth sm vwls nd thr wrds.

When using string variables in Python, we can easily perform string manipulation to change the value of the string variables.

One such manipulation is to remove certain characters from a string variable. For example, we can easily get rid of vowels from a string variable.

To delete vowels from a string in Python, you can use a regular expression search and replace using the Python sub() function from re module.

sub() will search a given string for a specific pattern and then replace the matches found with a given string.

Below is how you can remove vowels using sub() in Python.

import re

string_example = "This is a string with some vowels and other words."

string_without_vowels = re.sub("[aeiouAEIOU]","",string_example)

print(string_without_vowels)

#Output:
Ths s  strng wth sm vwls nd thr wrds.

Removing Vowels from String in Python with For Loop

Another way that you can remove all vowels from a string variable in Python is by defining a function that will check each character to see if it is a vowel or not and keep those that aren’t vowels.

To define this function, we will take in a string as an argument, and then return a newly created string.

To create the return string, we loop over each character and check if it is a vowel. If it is not a vowel, we append the character to the return string.

Below is an example of how you can remove vowels from a string using a loop in Python.

def removeVowels(str):
    new_str = ""
    for char in str:    
        if char not in ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'):
            new_str = new_str + char
    return new_str

string_example = "This is a string with some vowels and other words."

print(removeVowels(string_example))

#Output:
Ths s  strng wth sm vwls nd thr wrds.

Hopefully this article has been useful for you to learn how to remove vowels from strings in Python.

Categorized in:

Python,

Last Update: February 26, 2024