Python count() Method

Python 字符串Python String


Description

The Python count() method is used to count the number of occurrences of a character or substring in a string. The optional parameters are the start and end positions for the search in the string.

Syntax

Syntax of the count() method:

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

Parameters

  • sub -- the substring to search for
  • start -- the position in the string where the search starts. The default is the first character, whose index value is 0.
  • end -- the position in the string where the search ends. The index of the first character in the string is 0. The default is the last position of the string.

Return Value

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

Examples

The following example demonstrates 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 as follows:

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

Python 字符串Python String

Other Extensions