Python(四)装饰器、迭代器&生成器、re正则表达式、字符串格式化

本章内容:

  • 装饰器
  • 迭代器 & 生成器
  • re 正则表达式
  • 字符串格式化
装饰器

  装饰器是一个很著名的设计模式,经常被用于有切面需求的场景,较为经典的有插入日志、性能测试、事务处理等。装饰器是解决这类问题的绝佳设计,有了装饰器,我们就可以抽离出大量函数中与函数功能本身无关的雷同代码并继续重用。概括的讲,装饰器的作用就是为已经存在的对象添加额外的功能。

先定义一个基本的装饰器:

########## 基本装饰器 ##########
def orter(func):    #定义装饰器
    def inner():
        print("This is inner before.")
        s = func()    #调用原传入参数函数执行
        print("This is inner after.")
        return s        #return原函数返回值
    return inner      #将inner函数return给name函数

@orter    #调用装饰器(将函数name当参数传入orter装饰器)
def name():
    print("This is name.")
    return True        #name原函数return True 

ret = name()
print(ret)

输出结果:
This is inner before.
This is name.
This is inner after.
True

给装饰器传参数:

############ 装饰器传参数 ###########
def orter(func):
    def inner(a,b):      #接收传入的2个参数
        print("This is inner before.")
        s = func(a,b)    #接收传入的原函数2个参数
        print("This is inner after.")
        return s
    return inner

@orter
def name(a,b):    #接收传入的2个参数,并name整体函数当参数传入orter装饰器
    print("This is name.%s,%s"%(a,b))
    return True

ret = name('nick','jenny')    #传入2个参数
print(ret)

输出结果:
This is inner before.
This is name.nick,jenny
This is inner after.
True

给装饰器传万能参数:

########## 万能参数装饰器 ##########
def orter(func):
    def inner(*args,**kwargs):        #万能参数接收多个参数
        print("This is inner before.")
        s = func(*args,**kwargs)       #万能参数接收多个参数
        print("This is inner after.")
        return s
    return inner

@orter
def name(a,b,c,k1='nick'):        #接受传入的多个参数
    print("This is name.%s,%s"%(a,b))
    return True

ret = name('nick','jenny','car')
print(ret)

输出结果:
This is inner before.
This is name.nick,jenny
This is inner after.
True

一个函数应用多个装饰器方法:

########### 一个函数应用多个装饰器 #########

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            #将以下函数整体当参数传入orter装饰器  
@orter_2          #将以下函数当参数传入orter_2装饰器  
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)

输出结果:
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

  

迭代器 & 生成器

 1、迭代器

  迭代器只不过是一个实现迭代器协议的容器对象。

特点:

  1. 访问者不需要关心迭代器内部的结构,仅需通过next()方法不断去取下一个内容
  2. 不能随机访问集合中的某个值 ,只能从头到尾依次访问
  3. 访问到一半时不能往回退
  4. 便于循环比较大的数据集合,节省内存
>>> a = iter([1,2,3,4,5])
>>> a
<list_iterator object at 0x101402630>
>>> a.__next__()
1
>>> a.__next__()
2
>>> a.__next__()
3
>>> a.__next__()
4
>>> a.__next__()
5
>>> a.__next__()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration         #末尾生成StopIteration异常

2、生成器

  一个函数调用时返回一个迭代器,那这个函数就叫做生成器(generator);如果函数中包含yield语法,那这个函数就会变成生成器。

def xran():
    print("one")
    yield 1
    print("two")
    yield 2
    print("sr")
    yield 3

ret = xran()
#print(ret)      #<generator object xran at 0x00000000006ED308>

result = ret.__next__()
print(result)

result = ret.__next__()
print(result)

result = ret.__next__()
print(result)

# ret.__next__()  #循环完毕抛出StopIteration
#
# ret.close()     #关闭生成器

生成器表达式

>>>a=[7,8,9]
>>>b=[i**2 for i in a]
>>>b
[49, 64, 81]
>>>ib=(i**2 for i in a)
>>>ib
<generator object <genexpr> at 0x7f72291217e0>
>>>next(ib)
49
>>>next(ib)
64
>>>next(ib)
81
>>>next(ib)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

 

正则表达式

  正则表达式是用来匹配字符串非常强大的工具,在其他编程语言中同样有正则表达式的概念。就其本质而言,正则表达式(或 RE)是一种小型的、高度专业化的编程语言,(在Python中)它内嵌在Python中,并通过 re 模块实现。正则表达式模式被编译成一系列的字节码,然后由用 C 编写的匹配引擎执行。

#导入 re 模块
import re

s = 'nick jenny nice'

# 匹配方式(一)
b = re.match(r'nick',s)
q = b.group()
print(q)

# 匹配方式(二)
# 生成Pattern对象实例,r表示匹配源字符串
a = re.compile(r'nick')
print(type(a))               #<class '_sre.SRE_Pattern'>

b = a.match(s)
print(b)                     #<_sre.SRE_Match object; span=(0, 4), match='nick'>

q = b.group()
print(q)


#被匹配的字符串放在string中
print(b.string)              #nick jenny nice
#要匹配的字符串放在re中
print(b.re)                  #re.compile('nick')

  两种匹配方式区别在于:第一种简写是每次匹配的时候都要进行一次匹配公式的编译,第二种方式是提前对要匹配的格式进行了编译(对匹配公式进行解析),这样再去匹配的时候就不用在编译匹配的格式。

匹配规则:

  .
  "." 匹配任意字符(除了\n)
  \
  "\" 转义字符
  [...]
  "[...]" 匹配字符集

# "." 匹配任意字符(除了\n) a = re.match(r".","95nick") b = a.group() print(b) # [...] 匹配字符集 a = re.match(r"[a-zA-Z0-9]","123Nick") b = a.group() print(b)
  \d   
  匹配任何十进制数;它相当于类 [0-9]
  \D 
  匹配任何非数字字符;它相当于类 [^0-9]
  \s
  匹配任何空白字符;它相当于类 [\t\n\r\f\v]
  \S
  匹配任何非空白字符;它相当于类 [^\t\n\r\f\v]
  \w
  匹配任何字母数字字符;它相当于类 [a-zA-Z0-9]
  \W  
  匹配任何非字母数字字符;它相当于类 [^a-zA-Z0-9]
# \d \D 匹配数字/非数字
a = re.match(r"\D","nick")
b = a.group()
print(b)

# \s \S 匹配空白/非空白字符
a = re.match(r"\s"," ")
b = a.group()
print(b)

# \w \W 匹配单词字符[a-zA-Z0-9]/非单词字符
a = re.match(r"\w","123Nick")
b = a.group()
print(b)
a = re.match(r"\W","+-*/")
b = a.group()
print(b)
  *
   "*" 匹配前一个字符0次或者无限次
  +
   "+" 匹配前一个字符1次或者无限次
  ?
    "?" 匹配一个字符0次或者1次

   {m} {m,n}

    {m} {m,n} 匹配前一个字符m次或者m到n次

   *? +? ??

    *? +? ?? 匹配模式变为非贪婪(尽可能少匹配字符串)
# "*" 匹配前一个字符0次或者无限次
a = re.match(r"[A-Z][a-z]*","Aaaaaa123")    #可以只匹配A,123不会匹配上
b = a.group()
print(b)

# “+” 匹配前一个字符1次或者无限次
a = re.match(r"[_a-zA-Z]+","nick")
b = a.group()
print(b)

# “?” 匹配一个字符0次或者1次
a = re.match(r"[0-8]?[0-9]","95")   #(0-8)没有匹配上9
b = a.group()
print(b)

# {m} {m,n} 匹配前一个字符m次或者m到n次
a = re.match(r"[\w]{6,10}@qq.com","630571017@qq.com")
b = a.group()
print(b)

# *? +? ?? 匹配模式变为非贪婪(尽可能少匹配字符串)
a = re.match(r"[0-9][a-z]*?","9nick")
b = a.group()
print(b)
a = re.match(r"[0-9][a-z]+?","9nick")
b = a.group()
print(b)
   ^  
   "^" 匹配字符串开头,多行模式中匹配每一行的开头
   $
   "$" 匹配字符串结尾,多行模式中匹配每一行的末尾
   \A
   \A 仅匹配字符串开头
    \Z

   \Z 仅匹配字符串结尾

    \b

   \b 匹配一个单词边界,也就是指单词和空格间的位置
# "^" 匹配字符串开头,多行模式中匹配每一行的开头。
li = "nick\nnjenny\nsuo"
a = re.search("^s.*",li,re.M)
b = a.group()
print(b)

# "$" 匹配字符串结尾,多行模式中匹配每一行的末尾。
li = "nick\njenny\nnick"
a = re.search(".*y$",li,re.M)
b = a.group()
print(b)

# \A 仅匹配字符串开头
li = "nickjennyk"
a = re.findall(r"\Anick",li)
print(a)

# \Z 仅匹配字符串结尾
li = "nickjennyk"
a = re.findall(r"nick\Z",li)
print(a)

# \b 匹配一个单词边界,也就是指单词和空格间的位置
a = re.search(r"\bnick\b","jenny nick car")
b = a.group()
print(b)
  |
  "|" 匹配左右任意一个表达式
  ab
  (ab) 括号中表达式作为一个分组
  \<number>
  \<number> 引用编号为num的分组匹配到的字符串
  (?P<key>vlaue)
  (?P<key>vlaue) 匹配到一个字典,去vlaue也可做别名
  (?P=name)
  (?P=name) 引用别名为name的分组匹配字符串
# "|" 匹配左右任意一个表达式
a = re.match(r"nick|jenny","jenny")
b = a.group()
print(b)

# (ab) 括号中表达式作为一个分组
a = re.match(r"[\w]{6,10}@(qq|163).com","630571017@qq.com")
b = a.group()
print(b)

# \<number> 引用编号为num的分组匹配到的字符串
a = re.match(r"<([\w]+>)[\w]+</\1","<book>nick</book>")
b = a.group()
print(b)

# (?P<key>vlace) 匹配输出字典 
li = 'nick jenny nnnk'
a = re.match("(?P<k1>n)(?P<k2>\w+).*(?P<k3>n\w+)",li)
print(a.groupdict())
输出结果:
{'k2': 'ick', 'k1': 'n', 'k3': 'nk'}

# (?P<name>) 分组起一个别名
# (?P=name) 引用别名为name的分组匹配字符串
a = re.match(r"<(?P<jenny>[\w]+>)[\w]+</(?P=jenny)","<book>nick</book>")
b = a.group()
print(b)

 

 模块方法介绍:

  match

   从头匹配

  search

  匹配整个字符串,直到找到一个匹配


  findall

  找到匹配,返回所有匹配部分的列表

   finditer

  返回一个迭代器

  sub

  将字符串中匹配正则表达式的部分替换为其他值

  split

  根据匹配分割字符串,返回分割字符串组成的列表
######## 模块方法介绍 #########
# match 从头匹配

# search 匹配整个字符串,直到找到一个匹配

# findall 找到匹配,返回所有匹配部分的列表
# findall 加括号
li = 'nick jenny nick car girl'

r = re.findall('n\w+',li)
print(r)
#输出结果:['nick', 'nny', 'nick']
r = re.findall('(n\w+)',li)
print(r)
#输出结果:['nick', 'nny', 'nick']
r = re.findall('n(\w+)',li)
print(r)
#输出结果:['ick', 'ny', 'ick']
r = re.findall('(n)(\w+)(k)',li)
print(r)
#输出结果:[('n', 'ic', 'k'), ('n', 'ic', 'k')]
r = re.findall('(n)((\w+)(c))(k)',li)
print(r)
#输出结果:[('n', 'ic', 'i', 'c', 'k'), ('n', 'ic', 'i', 'c', 'k')]


# finditer 返回一个迭代器,和findall一样
li = 'nick jenny nnnk'
a = re.finditer(r'n\w+',li)
for i in a:
    print(i.group())

# sub 将字符串中匹配正则表达式的部分替换为其他值
li = 'This is 95'
a = re.sub(r"\d+","100",li)
print(a)

li = "nick njenny ncar ngirl"
a = re.compile(r"\bn")
b = a.sub('cool',li,3)      #后边参数替换几次
print(b)

#输出结果:
#coolick cooljenny coolcar ngirl

# split 根据匹配分割字符串,返回分割字符串组成的列表
li = 'nick,suo jenny:nice car'
a = re.split(r":| |,",li)   #或|
print(a)

li = 'nick1jenny2car3girl5'
a = re.compile(r"\d")
b = a.split(li)
print(b)

#输出结果:
#['nick', 'jenny', 'car', 'girl', '']   #注意后边空元素
  group()
  返回被 RE 匹配的字符串
  groups()
 
  返回一个包含正则表达式中所有小组字符串的元组,从 1 到所含的小组号
  groupdict()
 
  返回(?P<key>vlace)定义的字典
  start()
  返回匹配开始的位置
  end()
  返回匹配结束的位置
  span()
  返回一个元组包含匹配 (开始,结束) 的索引位置

li = 'nick jenny nnnk' a = re.match("n\w+",li) print(a.group()) a = re.match("(n)(\w+)",li) print(a.groups()) a = re.match("(?P<k1>n)(?P<k2>\w+).*(?P<k3>n\w+)",li) print(a.groupdict()) ----------------------------------------------- import re a = "123abc456" re.search("([0-9]*)([a-z]*)([0-9]*)",a).group(0) #123abc456,返回整体 re.search("([0-9]*)([a-z]*)([0-9]*)",a).group(1) #123 re.search("([0-9]*)([a-z]*)([0-9]*)",a).group(2) #abc re.search("([0-9]*)([a-z]*)([0-9]*)",a).group(3) #456 group(1) 列出第一个括号匹配部分,group(2) 列出第二个括号匹配部分,group(3)列出第三个括号匹配部分。 -----------------------------------------------
  re.I
  使匹配对大小写不敏感
  re.L
  做本地化识别(locale-aware)匹配
  re.M
  多行匹配,影响 ^ 和 $
  re.S  
  使 . 匹配包括换行在内的所有字符
  re.U
  根据Unicode字符集解析字符。这个标志影响 \w, \W, \b, \B.
  re.X
 
  注释,会影响空格(无效了)
#re.I	使匹配对大小写不敏感
a = re.search(r"nick","NIck",re.I)
print(a.group())

#re.L	做本地化识别(locale-aware)匹配
#re.U	根据Unicode字符集解析字符。这个标志影响 \w, \W, \b, \B.

#re.S:.将会匹配换行符,默认.逗号不会匹配换行符
a = re.findall(r".","nick\njenny",re.S)
print(a)
输出结果:
['n', 'i', 'c', 'k', '\n', 'j', 'e', 'n', 'n', 'y']

#re.M:^$标志将会匹配每一行,默认^只会匹配符合正则的第一行;默认$只会匹配符合正则的末行
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))

 

常见正则列子:

匹配手机号:

# 匹配手机号
phone_num = '13001000000'
a = re.compile(r"^1[\d+]{10}")
b = a.match(phone_num)
print(b.group())

匹配IPv4:

# 匹配IP地址
ip = '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 = a.search(ip)
print(b)

匹配email:

# 匹配 email
email = '630571017@qq.com'
a = re.compile(r"(.*){0,26}@(\w+){0,20}.(\w+){0,8}")
b = a.search(email)
print(b.group())

 

字符串格式化

1、百分号方式

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

 

 

  • (name)   可选,用于选择指定的key
  • flags    可选,可供选择的值有:width         可选,占有宽度
      • +     右对齐;正数前加正好,负数前加负号;
      • -     左对齐;正数前无符号,负数前加负号;
      • 空格  右对齐;正数前加空格,负数前加负号;
      • 0     右对齐;正数前无符号,负数前加负号;用0填充空白处
  • .precision  可选,小数点后保留的位数
  • typecode    必选
      • s,获取传入对象的__str__方法的返回值,并将其格式化到指定位置
      • r,获取传入对象的__repr__方法的返回值,并将其格式化到指定位置
      • c,整数:将数字转换成其unicode对应的值,10进制范围为 0 <= i <= 1114111(py27则只支持0-255);字符:将字符添加到指定位置
      • o,将整数转换成 八  进制表示,并将其格式化到指定位置
      • x,将整数转换成十六进制表示,并将其格式化到指定位置
      • d,将整数、浮点数转换成 十 进制表示,并将其格式化到指定位置
      • e,将整数、浮点数转换成科学计数法,并将其格式化到指定位置(小写e)
      • E,将整数、浮点数转换成科学计数法,并将其格式化到指定位置(大写E)
      • f, 将整数、浮点数转换成浮点数表示,并将其格式化到指定位置(默认保留小数点后6位)
      • F,同上
      • g,自动调整将整数、浮点数转换成 浮点型或科学计数法表示(超过6位数用科学计数法),并将其格式化到指定位置(如果是科学计数则是e;)
      • G,自动调整将整数、浮点数转换成 浮点型或科学计数法表示(超过6位数用科学计数法),并将其格式化到指定位置(如果是科学计数则是E;)
      • %,当字符串中存在格式化标志时,需要用 %%表示一个百分号
常用格式化:

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    【可选】空白处填充的字符
  • align   【可选】对齐方式(需配合width使用)
      • <,内容左对齐
      • >,内容右对齐(默认)
      • =,内容右对齐,将符号放置在填充字符的左侧,且只对数字类型有效。 即使:符号+填充物+数字
      • ^,内容居中
  • sign    【可选】有无符号数字
      • +,正号加正,负号加负;
      •  -,正号不变,负号加负;
      • 空格 ,正号空格,负号加负;
  • #       【可选】对于二进制、八进制、十六进制,如果加上#,会显示 0b/0o/0x,否则不显示
  • ,      【可选】为数字添加分隔符,如:1,000,000
  • width   【可选】格式化位所占宽度
  • .precision 【可选】小数位保留精度
  • type    【可选】格式化类型
      • 传入” 字符串类型 “的参数
        • s,格式化字符串类型数据
        • 空白,未指定类型,则默认是None,同s
      • 传入“ 整数类型 ”的参数
        • b,将10进制整数自动转换成2进制表示然后格式化
        • c,将10进制整数自动转换为其对应的unicode字符
        • d,十进制整数
        • o,将10进制整数自动转换成8进制表示然后格式化;
        • x,将10进制整数自动转换成16进制表示然后格式化(小写x)
        • X,将10进制整数自动转换成16进制表示然后格式化(大写X)
      • 传入“ 浮点型或小数类型 ”的参数
        • e, 转换为科学计数法(小写e)表示,然后格式化;
        • E, 转换为科学计数法(大写E)表示,然后格式化;
        • f , 转换为浮点型(默认小数点后保留6位)表示,然后格式化;
        • F, 转换为浮点型(默认小数点后保留6位)表示,然后格式化;
        • g, 自动在e和f中切换
        • G, 自动在E和F中切换
        • %,显示百分比(默认显示小数点后6位)
常用格式化:

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, 88888.1)

tpl = "i am {:s}, age {:d}, money {:0.2f}".format("nick", 18, 88888.111111111111)
  
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)

  

 

posted @ 2016-05-23 21:05  suoning  阅读(3763)  评论(4编辑  收藏  举报