Python - Word Replacement


Replacing the complete string or a part of string is a very frequent requirement in text processing. The replace() method returns a copy of the string in which the occurrences of old have been replaced with new, optionally restricting the number of replacements to max.

Following is the syntax for replace() method −

str.replace(old, new[, max])


  • old − This is old substring to be replaced.

  • new − This is new substring, which would replace old substring.

  • max − If this optional argument max is given, only the first count occurrences are replaced.

This method returns a copy of the string with all occurrences of substring old replaced by new. If the optional argument max is given, only the first count occurrences are replaced.


The following example shows the usage of replace() method.

str = "this is string!!! this is really string"
print (str.replace("is", "was"))
print (str.replace("is", "was", 3))


When we run above program, it produces the following result −

thwas was string!!! thwas was really string
thwas was string!!! thwas is really string

Replacement Ignoring Case

import re
sourceline  = re.compile("Tutor", re.IGNORECASE)
Replacedline  = sourceline.sub("Tutor","Tutorialspoint has the best tutorials for learning.")
print (Replacedline)

When we run the above program, we get the following output −

Tutorialspoint has the best Tutorials for learning.

Useful Video Courses


Python Online Training

187 Lectures 17.5 hours

Malhar Lathkar


Python Essentials Online Training

55 Lectures 8 hours

Arnab Chakraborty


Learn Python Programming in 100 Easy Steps

136 Lectures 11 hours

In28Minutes Official


Python with Data Science

Best Seller

75 Lectures 13 hours

Eduonix Learning Solutions


Python 3 from scratch to become a developer in demand

Best Seller

70 Lectures 8.5 hours

Lets Kode It


Python Data Science basics with Numpy, Pandas and Matplotlib

Most Popular

63 Lectures 6 hours

Abhilash Nelson