Python Basic Tutorial Notes-item 1-Instant tag-day4

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.