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, a character to replace, and a 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)

Program to Replace String Characters Example 2
In this Python program, we used For Loop to iterate every character in a String. Inside the For Loop, we are using the Python If Statement to check whether the Python String character is equal to ch or not. If true, this program replaces 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 character outputs is as shown below. Refer to the Python tutorial.
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 the Python 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
Also Read
- Python program to Remove Odd Characters in a String
- Python program to Remove Odd Index Characters in a String