Python3 replace () function usage, python3replace
Description
The replace () method replaces the old (old string) in the string with new (new String). If the third parameter max is specified, the replacement cannot exceed max.
Syntax
Replace () method Syntax:
Str. replace (old, new [, max])
Parameters
Old -- the substring to be replaced.
New -- new String, used to replace the old substring.
Max -- Optional string, cannot exceed max replacement
Return Value
Returns the new string generated after replacing old (old string) with new (new String). If the third parameter max is specified, the replacement cannot exceed max.
Instance
The following example shows how to use the replace () function:
#! /Usr/bin/python3 str = "Welcome to www.www.jb51.net" print (":", str) print (":", str. replace ("jb51.net", "jbzj.com") str = "this is string example .... wow !!! "Print (str. replace (" is "," was ", 3 ))
The output result of the above instance is as follows:
Old Address: www.jbzj.com
New address: www.jb51.net
Thwas was string example... wow !!!
Replace in python cannot replace strings
When replace is used to replace a string, you need to assign a value to the variable again. Because the string in python is an immutable object, you must assign a value again when using it.
Replace method in Python
There are two methods:
Last_date = "1/2/3" to "123"
One: repalce
Date = last_date.replace ('/','')
Ii. re
p = re.compile("/")date = p.sub('', last_date)
Note:
Do not escape, otherwise the function will not take effect.
Replace Method
Returns the copy of the string after text replacement based on the regular expression.
StringObj. replace (rgExp, replaceText)
Parameters
StringObj
Required. String object or String text to be replaced. The string is not modified by the replace method.
RgExp
Required. It is a regular expression object that contains the regular expression mode or available flag. It can also be a String object or text. If rgExp is not a regular expression object, it is converted to a string for exact search. Do not convert the string to a regular expression.
ReplaceText
Required. Is a String object or String text. For each position in stringObj that matches rgExp, it is replaced by the text contained in this object. In Jscript 5.5 or later versions, the replaceText parameter can also be a function that returns the replaced text.
For example:
Content. replace ('\ n ',''). replace ('\ R ',''). replace ('\\','\\\\'). replace (',','\\,')