Python Text Processing Useful Resources

Python Text Processing - 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])

Parameters

  • 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.

Example

Example - Usage of replace() method

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

main.py

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

Result

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

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

Example - Replacement Ignoring Case

main.py

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

Output

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

Tutorialspoint has the best Tutorials for learning.
Advertisements