---
title: "让python的字符串支持“findall”"
url: "https://lerry.me/post/2012/05/str-with-findall"
date: 2012-05-28T01:22:00.000Z
updated: 2026-09-01T09:08:11.158Z
tags:
  - "Python"
language: zh-CN
---

# 让python的字符串支持“findall”

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

```python
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
```

使用很简单

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

>>>[3, 5]
```
