Wednesday, December 25, 2024
Google search engine
HomeLanguagesPython – Replace all occurrences of a substring in a string

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 = “neveropen” s1 = “Lazyroar” s2 = “abcd” 
Output : test_str = “abcdforabcd” Explanation : We replace all occurrences of s1 with s2 in test_str. 

Input : test_str = “neveropen” s1 = “for” s2 = “abcd” 
Output : test_str = “LazyroarabcdLazyroar”

 Approach 1

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

Implementation using the inbuilt function:-

Python3




#Python has inbuilt function replace to replace all occurrences of substring.
input_string = "neveropen"
s1 = "Lazyroar"
s2 = "abcd"
input_string = input_string.replace(s1, s2)
print(input_string)


Output

abcdforabcd

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




#code for replacing all occurrences of substring s1 with new string s2
 
test_str="neveropen"
s1="Lazyroar"
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)
 
#contributed by Bhavya Koganti


Output

abcdforabcd

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):
    # Replacing all occurrences of substring s1 with s2
    test_str = re.sub(s1, s2, test_str)
    return test_str
 
 
# test
test_str = "neveropen"
s1 = "Lazyroar"
s2 = "abcd"
print(replace_substring(test_str, s1, s2))


Output

abcdforabcd

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):
    # Initialize an empty string to store the result
    result = ""
    # Initialize a variable to keep 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 want 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 = "neveropen"
s1 = "Lazyroar"
s2 = "abcd"
print(replace_substring(test_str, s1, s2))


Output

abcdforabcd

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.

RELATED ARTICLES

Most Popular

Recent Comments