在字符串ss中查找子串subsr的个数,并输出子串第一次出现的位置

2014-12-15 0 579
在字符串ss中查找子串subsr的个数,并输出子串第一次出现的位置
#coding= utf-8
def findStr(ss, substr):
    if ss.find(substr) == -1:
       print "not fund"
    else:
        res = []
        index = ss.find(substr)
        res.append(index)
        nlen = len(substr)
        ss = ss[index+nlen:]
        while ss != "":
              index = ss.find(substr)
              if index == -1:
                  return len(res),res[0]
              res.append(index)
              ss = ss[index+nlen:]
        return len(res),res[0]

if __name__ == "__main__":
    print findStr("fghabcjkabcabcghjabc", 'abc')

#res中的index对应的是每个ss[index+nlen:]中'abc'所在的位置,不是ss中的位置,只有第一个才是ss中出现的位置

遇见资源网 python 在字符串ss中查找子串subsr的个数,并输出子串第一次出现的位置 http://www.ox520.com/14960.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务