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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)) 

chevron_right


Output:

The original string is : geeksforgeeks
The string after swap : accdsforaccds

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

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 contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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 contribute@geeksforgeeks.org to report any issue with the above content.