Table of Contents

Replace Vowels in String with Python

Example Description
Learn how to replace all the vowels in a string with '*' in Python with this code. Input a string and get the modified string as output.

Introduction:

In this Python code example, we will learn how to replace all the vowels in a given string with ‘*’. This is a common string manipulation task, and this code will provide a solution to achieve it.

Code:

#Function to replace all vowels in the string with '*'
def replaceVowel(st):
 #create an empty string
 newstr = '' 
 for character in st:
  #check if next character is a vowel
  if character in 'aeiouAEIOU':
    #Replace vowel with * 
    newstr += '*' 
  else: 
    newstr += character
 return newstr
#end of function
st = input("Enter a String: ")
st1 = replaceVowel(st)
print("The original String is:",st)
print("The modified String is:",st1)

Logic:

  1. The code uses a function called ‘replaceVowel’ which takes a string as input.
  2. It iterates through each character in the string and checks if it is a vowel.
  3. If it is a vowel, it replaces the vowel with ‘*’.
  4. Finally, it returns the modified string.
  5. The code then prompts the user to enter a string, calls the function with the input string, and prints the original and modified strings.

Output:

 

Enter a String: Hello World

>> The original String is: Hello World

>> The modified String is: H*ll* W*rld