Search and match the specified text pattern in the string
For simple literal patterns , Use it directly
str.replace() The method can , such as ：
>>> text = 'yeah, but no, but yeah, but no, but yeah' >>> text.replace('yeah', 'yep') 'yep, but no, but yep, but no, but yep'
For complex patterns , Please use
sub() function . To illustrate this , Suppose you want to take the form
11/27/2012 The date string of is changed to
2012-11-27 . Examples are as follows ：
>>> text = 'Today is 11/27/2012. PyCon starts 3/13/2013.' >>> import re >>> re.sub(r'(\d+)/(\d+)/(\d+)', r'\3-\1-\2', text) 'Today is 2012-11-27. PyCon starts 2013-3-13.'
sub() The first parameter in the function is the matched pattern , The second parameter is replace mode . Backslash numbers like
\3 Point to the capture group number of the previous pattern .
If you plan to do multiple substitutions with the same pattern , Consider compiling it first to improve performance . such as ：
>>> import re >>> datepat = re.compile(r'(\d+)/(\d+)/(\d+)') >>> datepat.sub(r'\3-\1-\2', text) 'Today is 2012-11-27. PyCon starts 2013-3-13.'