Python literal replacement
Python Text Replacement
Replacing an entire string or part of a string is a very frequent requirement in text processing. The replace() method returns a copy of a string with all occurrences of the old string replaced by the new string, optionally limiting the number of replacements.
Below is the syntax of the replace() method:
str.replace(old, new[, max])
Parameters
- old – This is the old substring to be replaced.
-
new – This is the new substring to replace the old one.
-
max – If the optional max parameter is given, only the first count occurrences of the old substring are replaced.
This method returns a copy of a string with all occurrences of the old substring replaced by the new substring. If the optional argument max is given, only the first count occurrences of the old substring are replaced.
Example
The following example demonstrates the use of the replace() method.
str = "this is string example....wow!!! this is really a string"
print (str.replace("is", "was"))
print (str.replace("is", "was", 3))
Result
When we run the above program, it produces the following results:
thwas was string example....wow!!! thwas was really a string
thwas was string example....wow!!! thwas is really a string
Case-Insensitive Replacement
import re
sourceline = re.compile("Tutor", re.IGNORECASE)
Replacedline = sourceline.sub("Tutor", "Tutorialspoint has the best tutorials for learning.")
print (Replaced line)
When we run the above program, we get the following output −
Tutorialspoint has the best tutorials for learning.