Example analysis of the replace method in Python, pythonreplace
This article describes the replace method in Python as an example, which is of great practical value, as follows:
There are two replace methods:
Last_date = "1/2/3" target: "123"
Method 1: repalce
date =last_date.replace('/','')
Method 2: re
p = re.compile("/")date = p.sub('', last_date)
Note that do not escape, otherwise the function will not take effect.
The replace method returns the string copy after text replacement based on the regular expression. The format is as follows:
stringObj.replace(rgExp, replaceText)
Parameters:
StringObjRequired. String object or String text to be replaced. The string is not modified by the replace method.
RgExpRequired. 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.
ReplaceTextRequired. 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(',','\\,')
It is hoped that the examples described in this article will serve as a reference for everyone's Python program design.
In python3, the string does not have the replace method?
Replace is not a function of the string module, but a method of the String class.
S. replace ('hello', 'good ')
Pythonreplace
Def string_with2s (s): if not type (s) = type (''): raise TypeError slist = list (s) for I in range (0, len (slist ), 2): slist [I] = '2' return ''. join (slist) is a function and the call method is string_with2s (string)
For example, use the following statement
String_with_2s ('abcd ')
Returns the '2b2d 'string'