Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Python – Replace all occurrences of a substring in a string

  • Difficulty Level : Basic
  • Last Updated : 13 May, 2022

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
My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!