VOOZH about

URL: https://www.geeksforgeeks.org/python/python-string-count-method/

⇱ Python String count() Method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python String count() Method

Last Updated : 6 Nov, 2024

The count() method in Python returns the number of times a specified substring appears in a string. It is commonly used in string analysis to quickly check how often certain characters or words appear.

Let's start with a simple example of using count().


Output
2

Explanation: The letter "o" appears twice in the string "hello world", so count() returns 2.

Syntax of count() Method

string.count(substring, start = 0, end = len(s))

Parameters

  • substring (required): The substring we want to count within the original string.
  • start (optional): The index position in the string where the search should begin. Default is 0.
  • end (optional): The index position in the string where the search should stop. Default is the length of the string (i.e., up to the end).

Return Type

  • The count() method returns an integer representing the number of times the specified substring appears within the given range of the string.

Example of count() Method

Here are a few examples of count() method for better understanding.

Counting Words in String


Output
2

Finding Character Frequency in String


Output
4

Count Substring Occurrences with Start and End parameter


Output
1

Explanation: We set start=1 and end=20, so count() method will search for "apple" from the beginning up to index 20.

Related Articles:

Comment
Article Tags:
Article Tags: