python 自定义myCount函数,模拟实现 str.count()

str.count(“strs”) 统计 指定参数 在str中出现的次数

例子:

a="abdfdabfdabcfdfabds"
print(a.count("ab")) #4

自定义myCount()函数,来模拟实现 str.count() 的功能:

定义myCount()函数

def myCount(sourceStr,targetStr):
    leng=len(targetStr)
    total=0
    start=0
    end=leng
    dif=leng-1
    while True:
        res=sourceStr[start:end]
        # print(r)
        if res=="":
            break
        if res==targetStr:
            total+=1
        start += leng
        end += leng
        start -= dif
        end -= dif
    return total

测试:

a="abdfdabfdabcfdfabds"
print(myCount(a,"ab")) #4

------结束------

仅学习。

猜你喜欢

转载自blog.csdn.net/qq_52722885/article/details/126301669