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”

We use maketrans() and translate(). This is inbuild way to perform this task. This function maintains the table internally and performs the task of swapping.





# Python3 code to demonstrate working of 
# Swap Binary substring
# Using translate()
# initializing string
test_str = "geeksforgeeks"
# printing original string
print("The original string is : " + test_str)
# Swap Binary substring
# Using translate()
temp = str.maketrans("geek", "abcd")
test_str = test_str.translate(temp)
# printing result 
print("The string after swap : " + str(test_str)) 



The original string is : geeksforgeeks
The string after swap : accdsforaccds
My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :

Be the First to upvote.

Please write to us at to report any issue with the above content.