2007-06-25

 

Python Cookbook 1.19 判断一个字符串是否以指定字符串序列中的字符串结尾

需求:

给定一个字符串s和一个字符串序列set,判断该s是否以set中的字符串结尾,即s.endwith(str1)或s.endwith(str2)等等.其中str1和str2属于set.

讨论:

在Python中, itertools.imap方法可以很好的实现这个需求 :

import itertools
def anyTrue(predicate, sequence):
    return True in itertools.imap(predicate, sequence)
def endsWith(s, *endings):
    return anyTrue(s.endswith, endings)

对endWith的典型应用可能就是列出当前目录的图片文件了:

import os
for filename in os.listdir('.'):
    if endsWith(filename, '.jpg', '.jpeg', '.gif'):
       print filename

类似的,可以用同样的方法来处理同一类问题,anyTrue既方便又具有通用性.可以传递给它绑定方法来做字符串处理,如:
s.startwith或s.__contains__,当然,也可以直接编码:

if anyTrue(filename.endswith, (".jpg", ".gif", ".png")):

这样的可读性已经很好了.

相关说明:

绑定方法:

在Python中,如果对象具有方法,可以直接以对象的形式操作这个方法(比如,赋值,做为参数,做为返回值等)如:

L = ['fee', 'fie', 'foo']
x = L.append

这样x指向了L的一个绑定方法.调用x('fum')就等价于调用L.append('fum').
如果使用这个方法来取得类方法而不是实例的方法, 会获得非绑定方法.这样,当你调用时,需要传递对象做为第一个参数.比如:y=list.append
不能直接使用y.append('test'),因为Python并不知道要对哪一个对象进行操作.需要使用y(L,'test')来操作.



标签:


Comments: 发表评论



<< Home

This page is powered by Blogger. Isn't yours?