def count_self(s,x):
if not isinstance(s,str) and not isinstance(x,str):
return 0
n=len(x)
result=0
i=0
while i<len(s): #while的好处是可以控制遍历
if s[i:i+n]==x
result+=1
i+=n #如‘ccc’.count('cc'),跳过第1位(0开始),这样避免第1位和第2位组合
else:
i+=1
return result
自定义 s.count() #规避‘ccc‘.count(‘cc‘)的问题
于 2019-01-12 13:59:52 首次发布