Latest web development tutorials

Python3 count()方法

Python3 字符串 Python3字符串


描述

count() 方法用於統計字符串裡某個字符出現的次數。 可選參數為在字符串搜索的開始與結束位置。

語法

count()方法語法:

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

參數

  • sub -- 搜索的子字符串
  • start -- 字符串開始搜索的位置。 默認為第一個字符,第一個字符索引值為0。
  • end -- 字符串中結束搜索的位置。 字符中第一個字符的索引為0。 默認為字符串的最後一個位置。

返回值

該方法返回子字符串在字符串中出現的次數。

實例

以下實例展示了count()方法的實例:

#!/usr/bin/python3

str="www.w3big.com"
sub='o'
print ("str.count('o') : ", str.count(sub))

sub='run'
print ("str.count('run', 0, 10) : ", str.count(sub,0,10))

以上實例輸出結果如下:

str.count('o') :  3
str.count('run', 0, 10) :  1

Python3 字符串 Python3字符串