1、自定义字符串的count函数
>>> s = "Abcdb" >>> s.count("b") 2 >>> s.count("bc") 1 >>> s.count("bd") 0 >>> #可以包含重叠的字符 def str_count(string,sub_str): if (not isinstance(string,str)) or (not isinstance(sub_str,str)): return "string或sub_str不是字符串类型" sub_count = 0 sub_len = len(sub_str) #遍历 for i in range(len(string)): if string[i:i+sub_len] == sub_str: sub_count += 1 return sub_count print(str_count("Abcbcb","b")) print("Abcbcb".count("b")) print(str_count("Abcbcb","bc")) print("Abcbcb".count("bc")) print(str_count("bcbcb","bcb")) print("Abcbcb".count("bcb")) print(str_count("bcbcb123","123")) print("bcbcb123".count("123")) print(str_count("bcbcb123",int("123"))) print(
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)