Open In App

Python – Replace all occurrences of a substring in a string

Last Updated : 10 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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




#Python has inbuilt function replace to replace all occurrences of substring.
input_string = "geeksforgeeks"
s1 = "geeks"
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="geeksforgeeks"
s1="geeks"
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 = "geeksforgeeks"
s1 = "geeks"
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 = "geeksforgeeks"
s1 = "geeks"
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.



Next Article

Similar Reads

replace() in Python to replace a substring
Given a string str that may contain one more occurrences of “AB”. Replace all occurrences of “AB” with “C” in str. Examples: Input : str = "helloABworld" Output : str = "helloCworld" Input : str = "fghABsdfABysu" Output : str = "fghCsdfCysu" This problem has existing solution please refer Replace all occurrences of string AB with C without using ex
1 min read
Python Program to Replace all Occurrences of ‘a’ with $ in a String
Given a string, the task is to write a Python program to replace all occurrence of 'a' with $. Examples: Input: Ali has all aces Output: $li h$s $ll $ces Input: All Exams are over Output: $ll Ex$ms $re Over Method 1: uses splitting of the given specified string into a set of characters. An empty string variable is used to store modified string . We
3 min read
Python | All occurrences of substring in string
Many times while working with strings, we have problems dealing with substrings. This may include the problem of finding all positions of particular substrings in a string using Python. Let's discuss specific ways in which this task can be performed. Input: s = "GeeksforGeeks is best for Geeks", f = "Geeks" Output: [0, 8, 26] Explanation: The start
7 min read
Python - Replace all repeated occurrences with N
Sometimes, while working with Python list, we can have a problem in which we need to replace an element with another. But one can have variations of these such as increase of number and keeping the first occurrence. This can have applications in various domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using enumer
4 min read
Python | Get the starting index for all occurrences of given substring
Given a string and a substring, the task is to find out the starting index for all the occurrences of a given substring in a string. Let's discuss a few methods to solve the given task. Method #1: Using Naive Method C/C++ Code # Python3 code to demonstrate # to find all occurrences of substring in # a string # Initialising string ini_string = 'xbze
3 min read
Python - All occurrences of Substring from the list of strings
Given a list of strings and a list of substring. The task is to extract all the occurrences of a substring from the list of strings. Examples: Input : test_list = ["gfg is best", "gfg is good for CS", "gfg is recommended for CS"] subs_list = ["gfg", "CS"] Output : ['gfg is good for CS', 'gfg is recommended for CS'] Explanation : Result strings have
5 min read
Python | Replace characters after K occurrences
Sometimes, while working with Python strings, we can have a problem in which we need to perform replace of characters after certain repetitions of characters. This can have applications in many domains including day-day and competitive programming. Method #1: Using loop + string slicing This is brute force way in which this problem can be solved. I
5 min read
Python - Replace occurrences by K except first character
Given a String, the task is to write a Python program to replace occurrences by K of character at 1st index, except at 1st index. Examples: Input : test_str = 'geeksforgeeksforgeeks', K = '@' Output : geeksfor@eeksfor@eeks Explanation : All occurrences of g are converted to @ except 0th index. Input : test_str = 'geeksforgeeks', K = '#' Output : ge
5 min read
Python | Pandas Series.str.replace() to replace text in a series
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages that makes importing and analyzing data much easier. Pandas Series.str.replace() method works like Python .replace() method only, but it works on Series too. Before calling .replace() on a Panda
5 min read
Python | Replace substring in list of strings
While working with strings, one of the most used application is replacing the part of string with another. Since string in itself is immutable, the knowledge of this utility in itself is quite useful. Here the replacement of a substring in list of string is performed. Let's discuss certain ways in which this can be performed. Method #1 : Using list
6 min read
Practice Tags :
three90RightbarBannerImg