字符查找函数,返回该字符在字符串中位置

# -*- coding: utf-8 -*-
'''
This is a class used for finding all characters that a str contains.
The return value is a list.
'''
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

注意返回值是一个list,代表查找字符位置

s = super_str('nihaoa')
print s.findall('a')
<<<output:[3,5]

阅读更多
版权声明: https://blog.csdn.net/jipang6225/article/details/79974919
文章标签: python
个人分类: Python
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭