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 stringtest_str = "geeksforgeeks" # printing original stringprint("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


 (2).jpg)
