Python Program to Replace Character in String

This article deals with program in Python that replaces any particular character from a string with new character. Here string, and both old and new character must be entered by user at run-time. For example, if user enters programming as string, g as character to search, and x as character to replace. Therefore the new string becomes proxramminx.

Replace Old Character with New Character in String

The question is, write a Python program that replaces any specific character from a given string. The program given below is answer to this question:

print("Enter the String: ")
str = input()
print("Enter the old character to search for: ")
oldchar = input()
print("Enter the new character to replace with: ")
newchar = input()

str = str.replace(oldchar, newchar)
print("\nThe new string is: ")
print(str)

Here is its sample run. This is the initial output produced by above Python program:

python replace character in string

Now supply the inputs, say fresherearth as string, c as character to search for, and x as character to replace with. Here is its sample output after providing exactly same inputs:

replace character in string python

Modified Version of Previous Program

This program is created in a way that, if the entered old character is not available in the given string. Then program further doesn't ask to enter the new character to replace with, rather it produces a message saying the character does not found in given string and skip the rest execution of the program. Whereas if the character gets found, then the program executes in similar way as of previous program:

print("Enter the String: ", end="")
str = input()
print("Enter old character to search for: ", end="")
oldchar = input()

if oldchar not in str:
    print("\nThis character is not found in the string!")
else:
    print("Enter new character to replace with: ", end="")
    newchar = input()
    str = str.replace(oldchar, newchar)
    print("\nOld character replaced successfully!")
    print("\nThe new string is:", str)

Here is its sample run with user input, jobails.com as string, o as character to search, _ (underscore) as character to replace with:

replace old character with new in string python

Here is another sample run with user input, python as string and x as character to search. Since x is not available in the given string, therefore program displays the message and skip further receiving user input:

replace character with new character string python

Python Online Test


« Previous Program Next Program »