1. 程式人生 > 其它 >python字串-計數(count)

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.