Python Program to Replace Characters in a String

Write a Python program to Replace Characters in a String using the replace function and For Loop with an example.

Python Program to Replace Characters in a String

This program allows the user to enter a string, character to replace, and new character you want to replace with. Next, we used a built-in string function called replace to replace user given character with a new character.

str1 = input("Please Enter your Own String : ")
ch = input("Please Enter your Own Character : ")
newch = input("Please Enter the New Character : ")

str2 = str1.replace(ch, newch)

print("\nOriginal String : ", str1)
print("Modified String : ", str2)
Python program to Replace Characters in a String

Program to Replace String Characters Example 2

In this program program, we used For Loop to iterate every character in a Python String. Inside the For Loop, we are using If Statement to check whether the String character is equal to ch or not. If true, this program replace it with Newch

str1 = input("Please Enter your Own String : ")
ch = input("Please Enter your Own Character : ")
newch = input("Please Enter the New Character : ")

str2 = ''
for i in range(len(str1)):
if(str1[i] == ch):
str2 = str2 + newch
else:
str2 = str2 + str1[i]

print("\nOriginal String : ", str1)
print("Modified String : ", str2)

Replace the string characters outputs is as shown below.

Please Enter your Own String : tutorial gateway team
Please Enter your Own Character : t
Please Enter the New Character : P

Original String :   tutorial gateway team
Modified String :   PuPorial gaPeway Peam

Replace Characters in a String Example 3

This replaces string Characters code is the same as the above example. However, we are using For Loop with Object.

str1 = input("Please Enter your Own String : ")
ch = input("Please Enter your Own Character : ")
newch = input("Please Enter the New Character : ")

str2 = ''
for i in str1:
if(i == ch):
str2 = str2 + newch
else:
str2 = str2 + i

print("\nOriginal String : ", str1)
print("Modified String : ", str2)

Replacing the string characters output.

Please Enter your Own String : python programming examples
Please Enter your Own Character : o
Please Enter the New Character : G

Original String :   python programming examples
Modified String :   pythGn prGgramming examples