Different ways in python to remove vowels from a string

In this post, we will learn different ways to remove all vowels or a,e,i,o,u from a string.

Method 1: Iterate over the characters :

The idea is simple. We will iterate over the characters one by one, and if any character is vowel, we will replace it with an empty character. Below is the complete program :

import re

vowels = 'aeiouAEIOU'

given_str = input("Enter a string : ")
final_str = given_str

for c in given_str:
    if c in vowels:
        final_str = final_str.replace(c,"")

print(final_str)
  • vowels holds all the vowels in both lower and upper case.
  • given_str is the user input string. We have initialized one more variable final_str that holds the user input string in the beginning.
  • We are using one for loop to iterate over the characters. If any character is in the string vowels, we are replacing it with a blank character and assigning the result back to final_str.
  • Once the loop ends, we are printing the result i.e. final_str.

Sample Output :

Enter a string : Hello world !
Hll wrld !

Enter a string : HeLLO WORLD !!
HLL WRLD !!

Method 2: Using regular expression :

Python provides re module to work with regular expressions. This module has a lot of useful methods defined. One of its method sub is used to replace substrings in a string using a regular expression.

We will use this method to remove all vowels from a string with the help of regex.

This method is defined as below :

re.sub(pattern, repl, string, count=0, flags=0)

Here,

  • pattern is the regex pattern
  • repl is the replacement string
  • string is the string we are working on
  • count is the number of replacement we want.
  • flags are flags we are passing to the regex.

It returns the new modified string.

import re

vowels_pattern = r'[AEIOU]'

given_str = input("Enter a string : ")
final_str = re.sub(vowels_pattern, '', given_str, flags=re.IGNORECASE)

print(final_str)

Sample Output :

Enter a string : Hello Universe !
Hll nvrs !

Enter a string : Hello WORLD !
Hll WRLD !

Method 3: Using join :

This is simple, we will put all the characters of the string which are not vowel in an array and join them to a string.

import re

vowels = 'aeiouAEIOU'

given_str = input("Enter a string : ")
final_str = ''.join([ch for ch in given_str if ch not in vowels])

print(final_str)

It will give output as in the above examples.

Method 4: Using string translate :

translate method can be used to replace or translate characters in a string using a mapping table. In our case, the below example does that :

import re

vowels = 'aeiouAEIOU'

given_str = input("Enter a string : ")
translate = str.maketrans(dict.fromkeys(vowels))

final_str = given_str.translate(translate)

print(final_str)

It gives similar output :)

You might also like: