Latest web development tutorials

Python count () method

Python strings Python strings


description

Python count () method is used to count the number of times a character appears in a string. Optional parameters at the start and end of the string to search for.

grammar

count () method syntax:

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

parameter

  • Substring search - sub
  • start - beginning of the string search. The default is the first character, the first character index value of zero.
  • end - the end of the string search. Character index of the first character is 0. The default is the last position of the string.

return value

This method returns the number of substring in the string.

Examples

The following example shows an example of count () method:

#!/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)

Examples of the above output results are as follows:

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

Python strings Python strings