让python的字符串支持“findall”

最近在写程序时,出现了这样一个需求,查找出字符串中所有指定的关键词,str.find()只能找到一个,我想着标准库中应该有findall之类的函数吧,结果没找到,于是自己实现了一个,代码如下:

class super_str(str):
    """add support for findall()"""
    def __init__(self, arg):
        super(super_str, self).__init__()
        self.body = arg

    def findall(self, arg, start=0):
        body = self.body
        result = []        
        while True:
            pos = body.find(arg, start)
            if pos >= 0:
                result.append(pos)
                start = pos + len(arg)
                #body = body[pos+len(arg):]
                continue
            break
        return result

使用很简单

s = super_str('nihaoa')
print s.findall('a')

>>>[3, 5]
2,859 views, since 2012-05-28