Python – Replace all occurrences of a substring in a string
Sometimes, while working with Python strings, we can have a problem in which we need to replace all occurrences of a substring with other.
Input : test_str = “geeksforgeeks” s1 = “geeks” s2 = “abcd”
Output : test_str = “abcdsforabcds” Explanation : We replace all occurrences of s1 with s2 in test_str.
Input : test_str = “geeksforgeeks” s1 = “for” s2 = “abcd”
Output : test_str = “geeksabcdgeeks”
Approach:-
We can use inbuilt function replace present in python3 to replace all occurences of substring.
Implementation using the inbuilt function:-
Python3
#Python has inbuilt function replace to replace all occurences of substring. input_string = "geeksforgeeks" s1 = "geeks" s2 = "abcd" input_string = input_string.replace(s1, s2) print (input_string) |
Output
abcdforabcd