可以使用 Python 中的 count() 方法来统计字符串出现的次数。count() 方法返回指定字符串在字符串中出现的次数。
以下是示例代码:
def count_occurrence(string, sub_string):
count = string.count(sub_string)
return count
# 在字符串中查找 "apple" 子串出现的次数
string = "I have an apple, he has an apple, she has an apple too."
sub_string = "apple"
print(count_occurrence(string, sub_string)) # 输出:3
在上述代码中,count_occurrence() 函数接收两个参数,第一个是原始字符串,第二个是想要统计的子字符串。函数返回子字符串在原始字符串中出现的次数。
可以使用该函数来统计任意字符串中指定子字符串出现的次数。