Today we mainly look at the sub functions of the Re.sub function and the handler class.
First look at the Re.sub function
Re.sub a total of 5 parameters, but generally write the first three is good, that is, PATTERN,REPL and string
Pattern represents a modal string in a regular, repl can be a string, or it can be a function. String to be substituted for
Look at the code first:
Import Redef num2a (Match): Return ' a ' a = Re.sub (R ' (\d+) ', num2a, ' he123he ') print AA = Re.sub (R ' (\d+) ', R ' a ', ' he123he ') prin T A
Execution Result:
The code converts the string hehe123hehe to Heahe, respectively, through the function num2a and string A.
When the second argument of Re.sub is repl as a function, the return value of the function is the result that you want to replace.
And look at the sub function of handler.
Look at the following section of code
Import Reclass handler:def sub_emphasis (self, Match): return ' <em>%s</em> '% Match.group (1) def callback ( Self, prefix, name, *args): Method = GetAttr (self, prefix+name, None) if callable (method): Return Method (*args) def sub (self , name):d EF substitution (match): result = Self.callback (' sub_ ', name, match) if result is None:result = Match.group (0) retur n Resultreturn substitutiona = Handler () a = Re.sub (R ' \* (. +?) \* ', a.sub (' emphasis '), R ' This *is* a test ') print a
The result of the execution is:
You can see that the sub returns a new function, which is used as a replacement function in Re.sub.
It's wrong in the book.
If result is None:result = Match.group (0)
Not if result IsNone:match.group (0)
Because if the matching function is not found in the object, result will be none, so in order not to make any changes to the string, it should return the original method, that is, return Match.group (0)
Python Basic Tutorial Notes-item 1-Instant tag-day4