In the Python program, we will learn how to replace a character in a given string. Here we used the python built-in function replace()
to replace a character in a string and another way to do it is using loops.
Here is the source code of the program to replace a character in a given string.
Python Program to Replace a Character in a Given String Using replace() function
# Python Program to Replace a Character in a Given String Using replace() function
# Take the Input From the User
str1 = input("Enter the String: ")
ch = input("Enter the Character: ")
newch = input("Enter the New Character: ")
str2 = str1.replace(ch, newch)
print("\nOriginal String : ", str1)
print("Modified String : ", str2)
Enter the String: Tutorials Rack is an Online Learning Website
Enter the Character: r
Enter the New Character: s
Original String : Tutorials Rack is an Online Learning Website
Modified String : Tutosials Rack is an Online Leasning Website
# Python Program to Replace a Character in a Given String Using For Loop
# Take the Input From the User
str1 = input("Enter the String: ")
ch = input("Enter the Character: ")
newch = input("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)
Enter the String: Tutorials Rack is an Online Learning Website
Enter the Character: r
Enter the New Character: s
Original String : Tutorials Rack is an Online Learning Website
Modified String : Tutosials Rack is an Online Leasning Website
Python Program to Replace a Character in a Given String Using While Loop
# Python Program to Replace a Character in a Given String Using While Loop
# Take the Input From the User
str1 = input("Enter the String: ")
ch = input("Enter the Character: ")
newch = input("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)
Enter the String: Tutorials Rack is an Online Learning Website
Enter the Character: r
Enter the New Character: s
Original String : Tutorials Rack is an Online Learning Website
Modified String : Tutosials Rack is an Online Leasning Website
Comments