Friday, March 9, 2018

String replace() Method


String replace() Method in Python 3


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.


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

Return Value
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
#!/usr/bin/python3
str = "this is string example....wow!!! this is really string"
print (str.replace("is", "was"))
print (str.replace("is", "was", 3))
Result
thwas was string example....wow!!! thwas was really string
thwas was string example....wow!!! thwas is really string