Python字串count()方法

Python字串count()方法返回[start,end]範圍內子字串sub的出現次數。可選參數startend被解釋為切片符號。

語法

以下是count()方法的語法 -

str.count(sub, start = 0,end = len(string))

參數

  • sub - 這是要搜索的子字串。
  • start - 從此索引開始搜索。第一個字元索引是0。默認情況下,從0索引開始搜索。
  • end - 從此索引結束搜索。第一個字元索引是0。 默認情況下,搜索結束於最後一個索引。

返回值

  • 此方法返回[start,end]範圍內子字串sub的出現次數。

示例

以下示例顯示了count()方法的用法。

#!/usr/bin/python3
str = "this is string example....wow!!!"
sub = 'i'
print ("str.count('i') : ", str.count(sub))
sub = 'exam'
print ("str.count('exam', 10, 40) : ", str.count(sub,10,40))

當運行上面的程式,它產生以下結果 -

str.count('i') :  3
str.count('exam', 4, 40) :  1

上一篇: Python字串 下一篇: Python列表