Python 字符串 count() 方法
定义和用法
count() 方法返回指定值在字符串中出现的次数。
实例
例子 1
返回值 "apple" 在字符串中出现的次数:
txt = "I love apples, apple are my favorite fruit"
x = txt.count("apple")
print(x)
例子 2
从位置 10 到 24 进行检索:
txt = "I love apples, apple are my favorite fruit"
x = txt.count("apple", 10, 24)
print(x)
语法
string.count(value, start, end)
参数
| 参数 | 描述 |
|---|---|
| value | 必需。字符串。要检索的字符串。 |
| start | 可选。整数。开始检索的位置。默认是 0。 |
| end | 可选。整数。结束检索的位置。默认是字符串的结尾。 |