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
Program to replace a character in a string at a given index position
The program below allows the user to enter a string, index position, and the new character. If we have the index position, we can use a slicing technique to replace a substring or a character.
s = input("Enter a string: ")
pos = int(input("Enter index position: "))
ch = input("Enter a new character: ")
s = s[:pos] + ch + s[pos + 1:]
print(s)
Enter a string: Learn
Enter index position: 2
Enter a new character: M
LeMrn
Also Read