Details about Python decorator, iterator & generator, re regular expression, and string formatting

Source: Internet
Author: User
Tags python decorator
This article mainly describes the Python decorator, iterator & amp; Generator, re regular expression, and string formatting. if you are interested, refer to this chapter:

Decorator

Iterator & generator

Re regular expression

String formatting

Decorator

The decorator is a well-known design model and is often used in scenarios with cut-plane requirements. it is more classic in terms of log insertion, performance testing, and transaction processing. The decorator is an excellent design for solving such problems. with the decorator, we can extract a large number of identical codes irrelevant to the function itself and continue to reuse them. In summary, the purpose of the decorator is to add additional functions to existing objects.

First define a basic decorator:

########## Basic decorator ######### def orter (func): # define the decorator def inner (): print ("This is inner before. ") s = func () # call the original input parameter function to execute print (" This is inner after. ") return s # return original function return inner # return inner function to name function @ orter # Call decorator (pass function name as parameter to orter decorator) def name (): print ("This is name. ") return True # name Original function return True ret = name () print (ret) output result: This is inner before. this is name. this is inner after. true

Pass parameters to the decorator:

########### Parameters uploaded by the decorator ########### def orter (func): def inner (a, B): # receive two input parameters print ("This is inner before. ") s = func (a, B) # receives the input two original function parameters print (" This is inner after. ") return s return inner @ orterdef name (a, B): # receives two input parameters, and name the overall function. when the parameter is passed into the orter modifier print (" This is name. % s, % s "% (a, B) return True ret = name ('Nick ', 'Jenny') # Input Two parameters print (ret) to output the result: this is inner before. this is name. nick, jennyThis is inner after. true

Upload the following universal parameters to the decorator:

########## Omnipotent parameter decorator ########## def orter (func): def inner (* args, ** kwargs): # print ("This is inner before. ") s = func (* args, ** kwargs) # The omnipotent parameter receives multiple print (" This is inner after. ") return s return inner @ orterdef name (a, B, c, k1 = 'Nick '): # accept multiple input parameters print (" This is name. % s, % s "% (a, B) return True ret = name ('Nick ', 'Jenny', 'car') print (ret) output result: this is inner before. this is name. nick, jennyThis is inner after. true

The method for applying multiple decorators to a function is as follows:

########## Multiple decorators for a function application ######### def orter (func): def inner (* args, ** kwargs): print ("This is inner one before. ") print (" This is inner one before angin. ") s = func (* args, ** kwargs) print (" This is inner one after. ") print (" This is inner one after angin. ") return s return inner def orter_2 (func): def inner (* args, ** kwargs): print (" This is inner two before. ") print (" This is inner two before angin. ") s = func (* args, ** kwargs) print (" This is inner two after. ") print (" This is inner two after angin. ") return s return inner @ orter # pass the following functions as a parameter to the orter modifier @ orter_2 # pass the following functions as a parameter to the orter_2 modifier def name (a, B, c, k1 = 'Nick '): print ("This is name. % s and % s. "% (a, B) return True ret = name ('Nick ', 'Jenny', 'car') print (ret) output result: This is inner one before. this is inner one before angin. this is inner two before. this is inner two before angin. this is name. nick and jenny. this is inner two after. this is inner two after angin. this is inner one after. this is inner one after angin. true

Iterator & generator

1. iterator

The iterator is just a container object that implements the iterator protocol.

Features:

Visitors do not need to care about the internal structure of the iterator. they only need to use the next () method to retrieve the next content.

A value in the set cannot be randomly accessed, but can only be accessed from start to end in sequence

When half of the access traffic is reached, you cannot return back.

Easy to collect large data sets and save memory

a = iter([1,2,3,4])print aprint a.next()print a.next()print a.next()print a.next()print a.next()  
 
  1234Traceback (most recent call last):  File "D:/python/untitled4/test.py", line 23, in 
  
       print a.next()StopIteration
  
 

2. generator

When a function is called, an iterator is returned. This function is called a generator. if the function contains the yield syntax, this function becomes a generator.

Def xran (): print ("one") yield 1 print "two" yield 2 print "sr" yield 3 ret = xran () # print ret #
 
  
Result = ret. next () print result = ret. next () print result = ret. next () print result # ret. next () # throw an exception after the loop is completed # ret. close () # close the generator one1two2sr3
 

Generator expression:

a = [1,2,3]b = [i+3 for i in a]print bprint type(b)  ib = (i+3 for i in a)print ibprint ib.next()print ib.next()print ib.next()  [4, 5, 6]
 
  
    at 0x00000000023E8A20>456
  
 

Regular expression:

Regular expressions are powerful tools for matching strings. They are also used in other programming languages. In essence, a regular expression (or RE) is a small, highly specialized programming language (in Python) embedded in Python and implemented through the re module. The regular expression mode is compiled into a series of bytecode and then executed by the matching engine written in C.

# Import re module import re s = 'Nick jenny nice '# matching method (1) B = re. match (r 'Nick ', s) q = B. group () print (q) # matching method (2) # generate a Pattern object instance, and r indicates matching the source string a = re. compile (r 'Nick ') print (type ())#
 
  
B =. match (s) print (B) # <_ sre. SRE_Match object; span = (0, 4), match = 'Nick '> q = B. group () print (q) # put the matched string in string print (B. string) # nick jenny nice # put the string to be matched in re
 

The difference between the two matching methods is: the first abbreviation is that the matching formula must be compiled once for each matching, the second method is to compile (parse the matching formula) the format to be matched in advance, so that the matching format does not need to be compiled when matching again.

Matching Rules:


#". "Match any character (except \ n) a = re. match (r ". "," 95 nick ") B =. group () print (B) # [...] matching character set a = re. match (r "[a-zA-Z0-9]", "123 Nick") B =. group () print (B)

# \ D \ D match number/non-number a = re. match (r "\ D", "nick") B =. group () print (B) # \ s \ S match blank/non-blank character a = re. match (r "\ s", "") B =. group () print (B) # \ w \ W match word character [a-zA-Z0-9]/non-word character a = re. match (r "\ w", "123 Nick") B =. group () print (B) a = re. match (r "\ W", "+-*/") B =. group () print (B)

# "*" Matches the first character 0 times or unlimited times. a = re. match (r "[A-Z] [a-z] *", "Aaaaaa123") # can only match A, 123 won't match B =. group () print (B) # "+" matches the first character once or infinitely. a = re. match (r "[_ a-zA-Z] +", "nick") B =. group () print (B) # "?" Match a character 0 times or 1 time a = re. match (r "[0-8]? [0-9] "," 95 ") # (0-8) no matching on 9b =. group () print (B) # {m} {m, n} matches the previous character m times or m to n times a = re. match (r "[\ w] {6, 10} @ qq.com", "630571017@qq.com") B =. group () print (B )#*? +? ?? The matching mode changes to non-greedy (as few strings as possible) a = re. match (r "[0-9] [a-z] *? "," 9 nick ") B = a. group () print (B) a = re. match (r" [0-9] [a-z] +? "," 9 nick ") B = a. group () print (B)

# "^" Matches the start of a string. in multiline mode, the start of each row is matched. Li = "nick \ nnjenny \ nsuo" a = re. search ("^ s. * ", li, re. m) B =. group () print (B) # "$" matches the end of a string. in multiline mode, the end of each row is matched. Li = "nick \ njenny \ nnick" a = re. search (". * y $ ", li, re. m) B =. group () print (B) # \ A only matches the start of string li = "nickjennyk" a = re. findall (r "\ Anick", li) print (a) # \ Z only matches the end of the string li = "nickjennyk" a = re. findall (r "nick \ Z", li) print (a) # \ B matches a word boundary, that is, the position a = re between a word and a space. search (r "\ bnick \ B", "jenny nick car") B =. group () print (B)

# "|" Matches any expression a = re. match (r "nick | jenny", "jenny") B =. group () print (B) # (AB) the expression in parentheses acts as a group a = re. match (r "[\ w] {6, 10} @ (qq | 163 ). com "," 630571017@qq.com ") B =. group () print (B )#\
 
  
The string a = re. match (r "<([\ w] +>) [\ w] +
  Nick") B = a. group () print (B )#(? P
  
   
Vlace) match output dictionary li = 'Nick jenny nnnk 'a = re. match ("(? P
   
    
N )(? P
    
     
\ W + ).*(? P
     
      
N \ w +) ", li) print (. groupdict () output result: {'K2': 'ick', 'k1 ': 'N', 'k3': 'NK '}#(? P
      
        ) Group an Alias #(? P = name) the group matching string a = re. match (r "<(? P
       
         [\ W] +>) [\ w] +
        Nick") B = a. group () print (B)
       
      
     
    
   
  
 

Module method

######## Module method ######### match from the ground up # search matches the entire string until a match is found # findall finds a match, returns the list of all matched parts # findall brackets li = 'Nick jenny nick car girer' r = re. findall ('n' \ w + ', li) print (r) # output result: ['Nick', 'nny ', 'Nick'] r = re. findall ('(n \ w +)', li) print (r) # output result: ['Nick ', 'nny', 'Nick '] r = re. findall ('N' (\ w +) ', li) print (r) # output result: ['ick', 'ny', 'ick'] r = re. findall ('(n) (\ w +) (k)', li) print (r) # output result: [('N', 'IC ', 'k '), ('N', 'IC ', 'k')] r = re. findall ('(n) (\ w +) (c) (k)', li) print (r) # output result: [('N ', 'IC ',' I ', 'C', 'k'), ('N', 'IC', 'I', 'C', 'k')] # finditer returns an iterator. like findall, li = 'Nick jenny nnnk 'a = re. finditer (r 'n' \ w + ', li) for I in a: print (I. group () # sub replaces the part matching the regular expression in the string with another value li = 'This is 95 'a = re. sub (r "\ d +", "100", li) print (a) li = "nick njenny ncar ngirl" a = re. compile (r "\ bn") B =. sub ('cool ', li, 3) # print (B) after parameter replacement # output result: # coolick cooljenny coolcar ngirl # split string based on matching, returns the list composed of split strings: li = 'Nick, suo jenny: nice card' a = re. split (r ": |,", li) # or |, split:, blank character print (a) li = 'nick1jenny2car3girl5 'a = re. compile (r "\ d") B =. split (li) print (B) # output result: # ['Nick ', 'Jenny', 'car', 'Girl ', ''] # pay attention to the empty elements behind

Li = 'Nick jenny nnnk 'a = re. match ("n \ w +", li) print (. group () a = re. match ("(n) (\ w +)", li) print (. groups () a = re. match ("(? P
 
  
N )(? P
  
   
\ W + ).*(? P
   
    
N \ w +) ", li) print (. groupdict () ------------------------------------------------- import rea = "123abc456" re. search ("([0-9] *) ([a-z] *) ([0-9] *)", ). group (0) #123abc456, returns the overall re. search ("([0-9] *) ([a-z] *) ([0-9] *)", ). group (1) #123 re. search ("([0-9] *) ([a-z] *) ([0-9] *)", ). group (2) # abc re. search ("([0-9] *) ([a-z] *) ([0-9] *)", ). group (3) #456 group (1) lists the matching parts of the first parentheses, group (2) lists the matching parts of the second parentheses, and group (3) lists the matching parts of the third parentheses. -----------------------------------------------
   
  
 

# Re. I make the matching case insensitive

A = re. search (r "nick", "NIck", re. I)

Print (a. group ())

# Re. L local identification (locale-aware) matching

# Re. U parses characters according to the Unicode character set. This flag affects \ w, \ W, \ B, \ B.

# Re. S:. will match the line break. by default,. comma will not match the line break

A = re. findall (r ".", "nick \ njenny", re. S)

Print ()

Output result:

['N', 'I', 'C', 'K', '\ n', 'J', 'e', 'n', 'n ', 'Y']

# Re. M: ^ $ indicates that each row is matched. by default, ^ matches only the first row that matches the regular expression. by default, $ matches only the last row that matches the regular expression.

N = "" 12 drummers drumming,

11 pipers piping, 10 lords a-leaping """

P = re. compile ("^ \ d + ")

P_multi = re. compile ("^ \ d +", re. M)

Print (re. findall (p, n ))

Print (re. findall (p_multi, n ))

Common regular columns:

Matching mobile phone number:

# Match the mobile phone number phone_num = '000000' a = re. compile (r "^ 1 [\ d +] {10}") B =. match (phone_num) print (B. group ())

Match IPv4:

# Matching ip address = '192. 168.1.1 'a = re. compile (r "(1? [0-9]? [0-9]) | (2 [0-4] [0-9]) | (25 [0-5]) \.) {3} (1? [0-9]? [0-9]) | (2 [0-4] [0-9]) | (25 [0-5]) $ ") B =. search (ip) print (B)

Matching email:

# Matching emailemail = '2017 @ qq.com 'a = re. compile (r "(. *) {0, 26} @ (\ w +) {0, 20 }. (\ w +) {0, 8} ") B =. search (email) print (B. group ())

String formatting:

1. Percent sign method

% [(Name)] [flags] [width]. [precision] typecode

(Name) (optional) used to select the specified key

Flags is optional. optional values include: width (optional) and occupies width.

+ Right alignment; add positive values before positive values, and add negative numbers before negative values;

-Left alignment; unsigned before a positive number; added a negative number before a negative number;

Right alignment of spaces; add spaces before positive numbers, and add negative signs before negative numbers;

0: right alignment; positive: unsigned; negative: added before negative; blank space filled with 0

. Precision (optional) number of digits retained after decimal point

Typecode required

S, get the return value of the _ str _ method of the input object, and format it to the specified location

R, get the return value of the _ repr _ method of the input object, and format it to the specified location

C, integer: converts a number to its unicode value. The value range of decimal is 0 <= I <= 1114111 (py27 only supports 0-255). character: add characters to a specified position

O. convert the integer into an octal representation and format it to the specified position.

X. convert the integer to a hexadecimal representation and format it to the specified position.

D. convert integers and floating-point numbers into a decimal representation and format them to the specified position.

E. convert integers and floating-point numbers into scientific notation and format them to the specified position (lower case e)

E. convert integers and floating-point numbers into scientific notation and format them to the specified position (uppercase E)

F. convert integers and floating-point numbers to floating-point numbers and format them to the specified position (the default value is 6 digits after the decimal point)

F, same as above

G. it is automatically adjusted to convert integers and floating-point numbers into floating-point or scientific notation (more than 6 digits are counted in scientific notation ), format it to the specified position (e for scientific counting ;)

G. it is automatically adjusted to convert integers and floating-point numbers into floating-point or scientific notation (more than 6 digits are counted in scientific notation ), format it to the specified position (E for scientific counting ;)

%. When a formatted sign exists in the string, % must be used to indicate a percent sign.

Common formatting: tpl = "I am % s" % "nick" tpl = "I am % s age % d" % ("nick", 18) tpl = "I am % (name) s age % (age) d" % {"name": "nick", "age": 18} tpl = "percent %. 2f "% 99.97623 tpl =" I am % (pp ). 2f "% {" pp ": 123.425556,} tpl =" I am %. 2f % "% {" pp ": 123.425556 ,}

2. Format

[[Fill] align] [sign] [#] [0] [width] [,] [. precision] [type]

Fill [optional] characters filled in the blank space

Align [optional] align (which must be used with width)

<, Left-aligned content

>, Right-aligned content (default)

=, The content is right aligned, the symbol is placed on the left side of the fill character, and only valid for the number type. Even if: symbol + padding + number

^, Center content

Sign [optional] with or without a signed number

+, Positive and negative;

-The positive value remains unchanged, and the negative value is added to the negative value;

Space, positive space, negative plus negative;

# [Optional] for binary, octal, and hexadecimal systems, if # is added, 0b/0o/0x is displayed; otherwise, it is not displayed.

, [Optional] add a separator for a number, for example, 1,000,000

Width [optional] width occupied by the formatting bit

. Precision [optional] Decimal point retention precision

Type [optional] format type

Input "string type" parameter

Input "integer type" parameter

Input parameters of the float or decimal type

S: format string data.

Blank. If no type is specified, the default value is None, which is the same as s.

B. convert the decimal integer into a binary representation and format it.

C. convert a 10-in-10 integer to its corresponding unicode character

D, decimal integer

O. convert the decimal integer into an octal integer and format it;

X: convert the decimal integer into a hexadecimal representation and format it (lowercase x)

X: convert the decimal integer into a hexadecimal representation and format it (uppercase X)

E. convert to scientific notation (lower case e) and format it;

E. convert to scientific notation (uppercase E) and format it;

F. convert it to the floating point type (6 digits after the decimal point by default) and format it;

F. convert it to the floating point type (6 digits after the decimal point by default) and format it;

G, automatically switch between e and f

G, automatically switch between E and F

%, Display percentage (6 digits after decimal point by default)

Common formatting: tpl = "I am {}, age {},{}". format ("nick", 18, 'Jenny ') tpl = "I am {}, age {},{}". format (* ["nick", 18, 'Jenny ']) tpl = "I am {0}, age {1}, really {0 }". format ("nick", 18) tpl = "I am {0}, age {1}, really {0 }". format (* ["nick", 18]) tpl = "I am {name}, age {age}, really {name }". format (name = "nick", age = 18) tpl = "I am {name}, age {age}, really {name }". format (** {"name": "nick", "age": 18}) tpl = "I am {0 [0]}, age {0 [1]}, really {0 [2]} ". format ([1, 2, 3], [11, 22, 33]) tpl = "I am {: s}, age {: d}, money {: f }". format ("nick", 18,888 88.1) tpl = "I am {: s}, age {: d}, money {: 0.2f }". format ("nick", 18,888 88.1111111111) tpl = "I am {: s}, age {: d }". format (* ["nick", 18]) tpl = "I am {name: s}, age {age: d }". format (name = "nick", age = 18) tpl = "I am {name: s}, age {age: d }". format (** {"name": "nick", "age": 18}) tpl = "numbers: {: B}, {: o}, {: d }, {: x}, {: X}, {: % }". format (15, 15, 15, 15, 15, 15.87623, 2) tpl = "numbers: {0: B}, {0: o}, {0: d }, {0: x },{ 0: X },{ 0: % }". format (15) tpl = "numbers: {num: B}, {num: o}, {num: d}, {num: x}, {num: X }, {num: % }". format (num = 15)

The above is a detailed description of the Python decorator, iterator & generator, re regular expression, and string formatting. For more information, see other related articles in the first PHP community!

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.