Python Cookbook学习记录 ch1_19_2013/10/27

1.19检查字符串中的结束标记

系统有内建函数startswith()和endswith()来检查字符串的开始和结束字符

1 >>> s='hello'
2 >>> s.endswith('o')
3 True
4 >>> s.startswith('h')
5 True

本节使用方法检查字符串S中是否包含多个结束标记中的一个。文中推荐了一种快捷优雅的方法:

>>> import itertools
>>> def anyTrue(predicate,sequence):
    return True in itertools.imap(predicate,sequence)

>>> def endsWith(s,*endings):
    return anyTrue(s.endswith,endings)

>>> s = 'pic.jpg'
>>> endsWith(s,'.jpg','.bmp')
True

此方法最重要的便是使用了itertools.imap(),imap的作用是创建一个迭代器,生成项function(i1, i2, ..., iN),其中i1i2...iN分别来自迭代器iter1iter2 ... iterN,如果functionNone,则返回(i1, i2, ..., iN)形式的元组,只要提供的一个迭代器不再生成值,迭代就会停止。

此外endswith中的有一个参数是'*endings',作用是接受任意多个参数并保存在元祖中

>>> import itertools
>>> import math
>>> d = itertools.imap(math.sqrt,(2,4,8))
>>> for i in d:print i
1.41421356237
2.0
2.82842712475
>>> d = itertools.imap(math.pow,(1,2,3),(2,3,4))
>>> for i in d:print i
1.0
8.0
81.0

文中最后还介绍了“被绑定方法”(Bound Method)

如果是一个对象的方法,可以直接获得绑定到该对象的方法,并直接使用此方法:

>>> L=['A','B','C']
>>> x=L.append
>>> x('D')
>>> print L
['A', 'B', 'C', 'D']

如果是一个类方法,那么需要制定类的一个实例,因为解释器不清楚对哪个队形进行操作

>>> y=list.append
>>> y(L,'E')
>>> print L
['A', 'B', 'C', 'D', 'E']

 

 

posted on 2013-10-27 15:35  七海之风  阅读(152)  评论(0)    收藏  举报

导航