VOOZH about

URL: https://www.geeksforgeeks.org/python/python-replace-all-occurrences-of-a-substring-in-a-string/

⇱ Python - Replace all Occurrences of a Substring in a String - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python - Replace all Occurrences of a Substring in a String

Last Updated : 31 Oct, 2025

Given a string and a target substring, the task is to replace all occurrences of the target substring with a new substring. For Example:

Input: "python java python html python"
Replace "python" --> "c++"
Output: "c++ java c++ html c++"

Below are multiple methods to replace all occurrences efficiently.

Using replace()

The replace() method directly replaces all occurrences of a substring with the new string.


Output
c++ java c++ html c++

Explanation: a.replace(old, new) replaces every instance of old with new.

Using re.sub()

This method uses re.sub() to replace all matches of a pattern with the new substring. It is useful for complex patterns or multiple variations.


Output
c++ java c++ html c++

Explanation: re.sub(pattern, replacement, string) finds all occurrences of pattern and replaces them with replacement.

Using String Splitting and Joining

This method splits the string at each occurrence of the target and joins it back with the replacement. It works well but is less efficient for very long strings.


Output
c++ java c++ html c++

Explanation:

  • s.split(substring) splits the string into a list, removing the target substring.
  • "replacement".join(list) joins the parts with the replacement string.

Using a manual loop

This method builds a new string by checking each slice for the target substring. It is least efficient but works without built-in functions.


Output
c++ java c++ html c++

Explanation:

  • if s[i:i+len(target)] == target: Take a slice of the string from index i to i + len(target) and check if it matches the target substring.
  • res += replacement If a match is found, append the replacement string to res.
  • i += len(target) Move the index forward by the length of the target substring to skip the replaced part.
  • res += s[i] Append the current character to res.
  • i += 1 Move the index forward by 1 to continue checking the next character.
Comment
Article Tags: