python字符串-计数(count)


count函数用于统计字符串里某个子字符串出现的次数。

语法

S.count(sub[, start[, end]]) -> int

参数

  • sub: 搜索的子字符串。
  • start: 可选参数,开始搜索的位置。
  • end: 可选参数,结束搜索的位置。

返回值

  • 子字符串在字符串中出现的次数。

示例

str = 'abcabcd'
print('统计单个字符出现的次数:', str.count('a'))
print('统计单个字符出现的次数:', str.count('a', 1))
print('统计单个字符出现的次数:', str.count('a', 1, 3))
print('统计子字符串出现的次数:', str.count('ab'))
print('统计子字符串出现的次数:', str.count('df'))
统计单个字符出现的次数: 2
统计单个字符出现的次数: 1
统计单个字符出现的次数: 0
统计子字符串出现的次数: 2
统计子字符串出现的次数: 0

help()

Help on built-in function count:

count(...) method of builtins.str instance
    S.count(sub[, start[, end]]) -> int
    
    Return the number of non-overlapping occurrences of substring sub in
    string S[start:end].  Optional arguments start and end are
    interpreted as in slice notation.


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM