Python3 字符串Python3 字符串


描述

count() 方法用于統(tǒng)計(jì)字符串里某個(gè)字符出現(xiàn)的次數(shù)??蛇x參數(shù)為在字符串搜索的開始與結(jié)束位置。

語法

count()方法語法:

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

參數(shù)

  • sub -- 搜索的子字符串
  • start -- 字符串開始搜索的位置。默認(rèn)為第一個(gè)字符,第一個(gè)字符索引值為0。
  • end -- 字符串中結(jié)束搜索的位置。字符中第一個(gè)字符的索引為 0。默認(rèn)為字符串的最后一個(gè)位置。

返回值

該方法返回子字符串在字符串中出現(xiàn)的次數(shù)。

實(shí)例

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

#!/usr/bin/python3

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

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

以上實(shí)例輸出結(jié)果如下:

str.count('o') :  2
str.count('w3c', 0, 10) :  1

Python3 字符串Python3 字符串