A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python-replace-all-occurrences-of-a-substring-in-a-string/ below:

Python - Replace all occurrences of a substring in a string

Python - Replace all occurrences of a substring in a string

Last Updated : 12 Jul, 2025

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.

Python
a = "python java python html python"

res = a.replace("python", "c++")
print(res)

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

Explanation:

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.

Python
import re

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

Output
c++ java c++ html c++
Explanation: Using string splitting and joining

This approach involves splitting the string at the substring and rejoining the parts with the desired replacement.

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

A manual loop can iterate through the string and build a new one by replacing the target substring.

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:

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4