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 : 28 Apr, 2020

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)) 
Output:
The original string is : geeksforgeeks
The string after swap : accdsforaccds

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!