str.count()

Counts non-overlapping occurrences of a fragment in a string.

Returns
The number of occurrences.
Changes the original
No
On this page

Example

#
Python
text = "programming with python is enjoyable programming"

print(text.count("programming"))
print(text.count("o"))
print("aaaa".count("aa"))
Resultsaved result, you can check it
2
4
2

Definition and usage

#

The count() method returns the number of occurrences of the given fragment. Occurrences cannot overlap: in the string "aaaa", the fragment "aa" occurs twice, not three times.

The optional start and end arguments limit the counting to part of the string.

To count all distinct characters or words at once, collections.Counter is a better choice, it builds a dictionary of occurrences in a single pass.

Syntax

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

Parameters

#
  • sub

    str

    The fragment to count.
  • start, end

    int, optional

    The range to count within.

Good practices

#
  • To count many different elements at once, use Counter(text.split()).
  • Case matters. Convert the text to lowercase first if case should not matter.

Related entries

#

Spotted a mistake or missing an example? Write to us.