Python – Replace all occurrences of a substring in a string
Last Updated :
08 Jan, 2025
Improve
Replacing all occurrences of a substring in a string means identifying every instance of a specific sequence of characters within a string and substituting it with another sequence of characters.
Using replace()
replace () method is the most straightforward and efficient way to replace all occurrences of a substring in Python.
a = "python java python html python"
res = a.replace("python", "c++")
print(res)
Output
c++ java c++ html c++
Explanation:
- replace() method replaces all occurrences of the specified substring with the new string.
- This method is highly efficient for string replacement tasks and works seamlessly for all string sizes.
Let’s explore different methods to replace all occurrences of a substring in a string.
Using regular expressions
For complex patterns, regular expressions allow us to replace substrings based on a pattern.
import re
s = "python java python html python"
res = re.sub("python", "c++", s)
print(res)
Output
c++ java c++ html c++
Explanation:
- Regular expressions search for a specific pattern and replace all its matches with the replacement string.
- They are versatile and powerful for handling dynamic or complex patterns.
Using string splitting and joining
This approach involves splitting the string at the substring and rejoining the parts with the desired replacement.
s = "python java python html python"
res = "c++".join(s.split("python"))
print(res)
Output
c++ java c++ html c++
Explanation:
- split() method breaks the string into parts using the target substring.
- join() method combines these parts with the replacement string.
- While functional, this method is less efficient than replace for simple replacements.
Using a manual loop
A manual loop can iterate through the string and build a new one by replacing the target substring.
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:
- This method manually searches for the target substring and replaces it with the desired string.