Python str.count() 方法用于统计子串在字符串中出现的次数。
语法
s.count(sub, start=0, end=len(s))参数
sub:要统计的子串。可选 start/end:统计范围。
返回值
返回子串出现次数(整数,不重叠计数)。
示例
print("banana".count("a")) # 3
print("hello hello".count("hello")) # 2
print("aaa".count("aa")) # 1,不重叠计数
print("Python".count("x")) # 0
sentence = "the quick brown fox jumps over the lazy dog"
print(sentence.count("the")) # 2输出:
3
2
1
0
2注意事项
count 不统计重叠匹配("aaa" 里 "aa" 只算 1 次)。