Python – Replace all occurrences of a substring in a string
Last Updated :
10 Mar, 2023
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
input_string = "geeksforgeeks"
s1 = "geeks"
s2 = "abcd"
input_string = input_string.replace(s1, s2)
print (input_string)
|
Time Complexity: O(n)
Auxiliary Space: O(n)
Approach 2:
Splitting the string by substring and then replacing with the new string.split() function is used.
Python3
test_str = "geeksforgeeks"
s1 = "geeks"
s2 = "abcd"
s = test_str.split(s1)
new_str = ""
for i in s:
if (i = = ""):
new_str + = s2
else :
new_str + = i
print (new_str)
|
The Time and Space Complexity for all the methods are the same:
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 3: Another approach to replace all occurrences of a substring in a string is to use the re.sub() function from the re module in python.
Python3
import re
def replace_substring(test_str, s1, s2):
test_str = re.sub(s1, s2, test_str)
return test_str
test_str = "geeksforgeeks"
s1 = "geeks"
s2 = "abcd"
print (replace_substring(test_str, s1, s2))
|
Time Complexity: O(n), where n is the length of the input string. This is because the re.sub() function iterates through the entire input string and performs a regular expression match on each character to find all occurrences of the substring. The number of iterations is directly proportional to the length of the input string.
Auxiliary Space:New
Method 4: Using simple iteration
The idea behind this approach is to iterate through the input string character by character and check if each substring of length m matches the substring we want to replace. If it does, we add the replacement substring to our result and move the pointer forward by m characters. If it doesn’t match, we add the current character to the result and move the pointer forward by 1 character.
Python3
def replace_substring(test_str, s1, s2):
result = ""
i = 0
while i < len (test_str):
if test_str[i:i + len (s1)] = = s1:
result + = s2
i + = len (s1)
else :
result + = test_str[i]
i + = 1
return result
test_str = "geeksforgeeks"
s1 = "geeks"
s2 = "abcd"
print (replace_substring(test_str, s1, s2))
|
Time complexity: O(nm), where n is the length of the input string and m is the length of the substring to be replaced.
Auxiliary space: O(n), since we are creating a new string to store the result.
Please Login to comment...