Replace Occurrences of a Substring in String with Python
Introduction
Replacing all or n occurrences of a substring in a given string is a fairly common problem of string manipulation and text processing in general. Luckily, most of these tasks are made easy in Python by its vast array of built-in functions, including this one.
Let’s say, we have a string that contains the following sentence:
The brown-eyed man drives a brown car.
Our goal is to replace the word "brown"
with the word "blue"
:
The blue-eyed man drives a blue car.
In this article, we’ll be using the replace()
function as well as the sub()
and subn()
functions with patterns to replace all occurrences of a substring from a string.
replace()
The simplest way to do this is by using the built-in function – replace()
:
string.replace(oldStr, newStr, count)
The first two parameters are required, while the third one