Python Replace all Occurrences of a Substring in a String (original) (raw)

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)

`

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.

Python `

import re s = "python java python html python" res = re.sub("python", "c++", s) print(res)

`

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.

Python `

s = "python java python html python" res = "c++".join(s.split("python")) print(res)

`

Output

c++ java c++ html c++

**Explanation:

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)

`

Output

c++ java c++ html c++

**Explanation: