Count() Function Of Str Class

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:

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: 

Number of times substring occured:1

Number of times substring occured:3

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

 

 


Copyright 2023 © pythontic.com