Python Program to Replace all Vowels with given Character

This article is created to cover some programs in Python that find and replaces all vowels available in a given string with a given character. For example, if string codescracker and a character x is entered by user, then all the vowels from codescracker gets replaced with x. Therefore, the final string after replacing vowels becomes cxdxscrxckxr

Replace all Vowels with given Character

The question is, write a Python program to replace all vowels from string with a character. The string and character must be entered by user at run-time. The program given below is answer to this question:

print("Enter the String: ")
str = input()

print("Enter a character: ")
char = input()

newstr = ""
for i in range(len(str)):
    if str[i]=='a' or str[i]=='e' or str[i]=='i' or str[i]=='o' or str[i]=='u':
        newstr = newstr + char
    else:
        newstr = newstr + str[i]

print("\nOriginal String:", str)
print("New String:", newstr)

Here is its sample run:

python replace vowel with character

Now provide the input say how are you as string and x as character to replace all the vowels available in the given string with x like shown in the sample output given below:

replace vowels with given character python

Note - The program given above only correct for lowercase string input. Since we've not included the uppercase vowels in condition checking part. Since we've another program given below, which is the modified version of previous program.

Modified Version of Previous Program

This program uses list to store all the vowels (including uppercase). Using this list, we've checked whether the character at current index is in the list (where vowels are stored) or not. Based on the condition, we've done the job of replacing the vowel with given character like shown in the program given below:

print("Enter a String: ", end="")
str = input()

print("Enter a character to replace all vowels with it: ", end="")
char = input()

newstr = ""
vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']

for i in range(len(str)):
    if str[i] in vowels:
        newstr = newstr + char
    else:
        newstr = newstr + str[i]

print("\nOriginal String =", str)
print("New String =", newstr)

Here is its sample run with user input, Python Programming as string and _ (underscore) as character to replace all vowels with it:

replace all vowels with character python

Python Online Test


« Previous Program Next Program »


Liked this post? Share it!