Python – Replacing Words

Python – Replacing Words

In text processing, replacing a string completely or partially is a frequent requirement. The replace() method returns a copy of a string where all occurrences of the old string are replaced with the new string, optionally limiting the number of replacements to max.

Below is the syntax of the replace() method −

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

Parameters

  • old − This is the old string to be replaced.
  • new − The new string that will replace the old string.

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

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

Example

The following example demonstrates the use of the replace() method.

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

Result

Running the above program will produce the following result.

thwas was the string example....wow!!! thwas was really a string
thwas was the string example....wow!!! thwas is really a string

Case-Ignoring Replacement

import re
sourceline = re.compile("Tutor", re.IGNORECASE)

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

Running the above program will produce the following output.

Tutorialspoint has the best tutorials for learning.

Leave a Reply

Your email address will not be published. Required fields are marked *