Python3 replace() Method
Description
The replace() method replaces old (old string) in the string with new (new string). If the third parameter max is specified, the replacement will not exceed max times.
Syntax
The syntax of the replace() method is:
str.replace(old, new[, max])
Parameters
- old -- The substring to be replaced.
- new -- The new string, used to replace the old substring.
- max -- Optional string; replacement will not exceed max times.
Return Value
Returns the new string generated after replacing old (old string) with new (new string) in the string. If the third parameter max is specified, the replacement will not exceed max times.
Examples
The following example demonstrates how to use the replace() function:
Example
#!/usr/bin/python3
str = "www.w3cschool.cc"
print ("Example Tutorial old address:", str)
print ("Example Tutorial new address:", str.replace("w3cschool.cc", "example.com"))
str = "this is string example....wow!!!"
print (str.replace("is", "was", 3))
The output of the above example is as follows:
Example旧地址: www.w3cschool.cc Example新地址: www.example.com thwas was string example....wow!!!
Other Extensions
Python3 Strings