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.
posted @ 2022-04-05 19:46  freepc  阅读(2583)  评论(0)    收藏  举报