Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python count() method

Python count() method

Python Strings Python Strings


Description

The Python count() method counts the number of times a character or substring appears in a string. The optional parameters specify the start and end positions for the search.

Syntax

count() method syntax:


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

Parameters

Return Value

This method returns the number of times the substring occurs in the string.

Example

The following example shows how to use the count() method:

Example (Python 2.0+)

#!/usr/bin/python

str

=

"

this is string example....wow!!!

"

;

sub

=

"

i

"

;

print

"

str.count(sub, 4, 40) :

"

,

str

.

count

(

sub

,

4

,

40

)

sub

=

"

wow

"

;

print

"

str.count(sub) :

"

,

str

.

count

(

sub

)

The output of the above example is:


str.count(sub, 4, 40) :  2
str.count(sub) :  1

Python Strings Python Strings