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