Skip to content
Related Articles

Related Articles

Python – Replace all occurrences of a substring in a string

View Discussion
Improve Article
Save Article
Like Article
  • Difficulty Level : Basic
  • Last Updated : 22 Jun, 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 = “abcdforabcd” 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 1

We can use inbuilt function replace present in python3 to replace all occurrences of substring.

Implementation using the inbuilt function:-

Python3




#Python has inbuilt function replace to replace all occurrences of substring.
input_string = "geeksforgeeks"
s1 = "geeks"
s2 = "abcd"
input_string = input_string.replace(s1, s2)
print(input_string)

Output

abcdforabcd

Approach 2:

Splitting the string by substring and then replacing with the new string.split() function is used.

Python3




#code for replacing all occurences of substring s1 with new string s2
 
test_str="geeksforgeeks"
s1="geeks"
s2="abcd"
 
#string split by substring
s=test_str.split(s1)
new_str=""
 
for i in s:
    if(i==""):
        new_str+=s2
    else:
        new_str+=i
 
#printing the replaced string
print(new_str)
 
#contributed by Bhavya Koganti

Output

abcdforabcd


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!