Python – Replace all occurrences of a substring in a string

Sometimes, when 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 = “CodesForCodes” s1 = “Codes” s2 = “Test”
Output : test_str = “TestforTest” Explanation: We replace all occurrences of s1 with s2 in test_str.

Input : test_str = “CodeConfigCode” s1 = “for” s2 = “ABC”
Output : test_str = “ABCConfigABC”

Approach 1

We can use inbuilt function/method replace present in python3 to replace all occurrences of substring.

Implementation using the inbuilt function: –

Python3


#Python has inbuilt function/method replace to replace all occurrences of substring.
input_string = "CodeConfigCode"
s1 = "Code"
s2 = "abcd"
input_string = input_string.replace(s1, s2)
print(input_string)


Output

abcdCofigabcd

Time Complexity: O(n)
Auxiliary Space: O(n)

Approach 2:

Splitting the string by substring and then replacing with the new string.split() function/method is used.

Python3

#code for replacing all occurrences of substring s1 with new string s2
test_str="CodeConfigCode"
s1="Code"
s2="abcd"
#string split by substring
s=test_str.split(s1)
new_str=""
for i in s:
    if(i==""):
        new_str+=s2
    else:
        new_str+=i
#printing the replaced string
print(new_str)


Output

abcdConfigabcd

The Time and Space Complexity for all the functions/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/method from the re module in python.

Python3

import re
def replace_substring(test_str, s1, s2):
    # Replacing all occurrences of substring s1 with s2
    test_str = re.sub(s1, s2, test_str)
    return test_str
# test
test_str = "CodeConfig"
s1 = "Code"
s2 = "abcd"
print(replace_substring(test_str, s1, s2))


Output

abcdConfig

Time Complexity: O(n), where n is the length of the input string. This is because the re.sub() function/method iterates through the entire input string and performs a regular expression match enabled 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 may be interested 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):
    # Initialize an empty string to store the result
    result = ""
    # Initialize a variable to Keep the track of our position in the string
    i = 0
    # Loop through the string one character at a time
    while i < len(test_str):
        # Check if the current substring matches the substring we may be interested to replace
        if test_str[i:i+len(s1)] == s1:
            # If it does, add the replacement substring to the result and move the pointer forward
            result += s2
            i += len(s1)
        else:
            # If it doesn't, add the current character to the result and move the pointer forward
            result += test_str[i]
            i += 1
    # Return the final result
    return result
# test
test_str = "CodeConfig"
s1 = "Code"
s2 = "abcd"
print(replace_substring(test_str, s1, s2))


Output

abcdConfig

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.

Explore More

Python 10 Programs for Beginners

Program 1:Write a program to create a 2D array using NumPy. Output: Program 2: Write a program to convert a python list to a NumPy array. Output: Program 3: Write a program to create matrix of 3×3 from 11 to 30. Output: Program 4: Write a program to create a data frame to store data of candidates who appeared in

Find index of first occurrence when an unsorted array is sorted

Find index of first occurrence when an unsorted an array is sorted Given an unsorted an array and a number x, find an index of first occurrence of x when

Find sum non repeating distinct elements array

Find sum of non-repeating (distinct) elements in an array Given an integer an array with repeated elements, the task is to find the sum of all distinct elements in the