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.
Python
a = "python java python html python"
res = a.replace("python", "c++")
print(res)
Outputc++ 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.
Python
import re
s = "python java python html python"
res = re.sub("python", "c++", s)
print(res)
Outputc++ 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.
Python
s = "python java python html python"
res = "c++".join(s.split("python"))
print(res)
Outputc++ 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.
Python
s = "python java python html python"
target = "python"
replacement = "c++"
res = ""
i = 0
while i < len(s):
if s[i:i+len(target)] == target:
res += replacement
i += len(target)
else:
res += s[i]
i += 1
print(res)
Outputc++ 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.
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice