Python 的 str.count(~) 方法计算字符串中子字符串的非重叠出现次数。
参数
1. sub | string
您想要计算出现次数的子字符串。
2. start | number | optional
开始计数的源字符串的起始索引(包含)。默认情况下,0 。
3. end | number | optional
停止计数的源字符串的索引(不包括)。默认情况下,len(source string) 。
返回值
源字符串中 sub 不重叠出现的次数。
例子
基本用法
计算子字符串 "e" 在 "Awesome" 中出现的次数:
x = "Awesome"
x.count("e")
2
计算子字符串 "aa" 在 "aaa" 中出现的次数:
y = "aaa"
y.count("aa")
1
返回的计数是1,因为我们只计算非重叠的出现次数。
启动参数
计算从索引1(含)开始的子字符串"ab"的出现次数:
z = "abcd"
z.count("ab", 1)
0
由于搜索仅从索引 1 ( "b" ) 开始,因此我们不会返回任何匹配的 "ab" 。
结束参数
要在索引 2 处停止计数(不包括):
w = "abcd"
w.count("bc", 0, 2)
0
由于搜索结束于索引 2 ("c"),并且不包括索引 2 ("c"),因此我们不会返回 "bc" 的任何匹配项。
相关用法
- Python String count()用法及代码示例
- Python String casefold()用法及代码示例
- Python String capitalize方法用法及代码示例
- Python String center()用法及代码示例
- Python String casefold方法用法及代码示例
- Python String center方法用法及代码示例
- Python String capitalize()用法及代码示例
- Python String isnumeric方法用法及代码示例
- Python String Center()用法及代码示例
- Python String zfill方法用法及代码示例
- Python String rstrip方法用法及代码示例
- Python String decode()用法及代码示例
- Python String join()用法及代码示例
- Python String isalnum()用法及代码示例
- Python String endswith方法用法及代码示例
- Python String rsplit()用法及代码示例
- Python String isidentifier()用法及代码示例
- Python String startswith()用法及代码示例
- Python String rjust方法用法及代码示例
- Python String rpartition()用法及代码示例
- Python String rpartition方法用法及代码示例
- Python String ljust方法用法及代码示例
- Python String splitlines()用法及代码示例
- Python String upper()用法及代码示例
- Python String isprintable()用法及代码示例
注:本文由纯净天空筛选整理自Isshin Inada大神的英文原创作品 Python String | count method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
