count() function of str class

The count function of str class in Python returns the number of time a substring occurs in a given string.Start and stop positions can be specified.

Str Updated 10 Mar 2017 1 min read

Method Name

count

Method Signature

count(sub[, start[, end]])

Method Overview

  • The method count() of str class returns the number of occurrences of a substring.

  • The count method can be supplied with start and end positions for the substring search.

  • When the start position and stop position are specified search for the substring starts and stops at the specified positions.

Example

python
pangram        = "The quick brown fox jumps over the lazy dog"

strint2Count   = "fox"

occurences     = pangram.count(strint2Count)

print("Number of times substring occured:{}".format(occurences))

mainString      = "The man we saw saw a saw"

strint2Count    = "saw"

occurences      = mainString.count(strint2Count)

print("Number of times substring occured:{}".format(occurences))

# Specify the start and stop positions of the string

occurences      = mainString.count(strint2Count, 15, len(mainString))

print("Number of times substring occured(with start and stop specified):{}".format(occurences))

Output

Output
Number of times substring occured:1

Number of times substring occured:3

Number of times substring occured(with start and stop specified):2