Python str.count() function


str.count() Function in Python

The str.count() function in Python is used to count the number of occurrences of a specified substring within a string. This function is useful for determining how many times a particular substring appears in a string.

Syntax:

string.count(substring, start, end)
  • substring: The substring you want to count.
  • start (optional): The starting index from where the count should begin. The default is 0.
  • end (optional): The ending index where the count should stop. The default is the end of the string.

Example 1: Basic usage

# Example 1: Counting occurrences of a substring my_string = "Hello, world! Hello, everyone!" count = my_string.count("Hello") print(count) # Output: 2

In this example:

  • The substring "Hello" appears 2 times in the string.

Example 2: Specifying start and end indices

# Example 2: Specifying start and end indices my_string = "banana" count = my_string.count("a", 1, 5) # Count 'a' from index 1 to index 5 print(count) # Output: 2

Here:

  • The count of "a" is done only within the substring "anan" (from index 1 to index 5), resulting in 2 occurrences.

Example 3: Case sensitivity

# Example 3: Case sensitivity my_string = "Hello, world! hello, everyone!" count = my_string.count("hello") print(count) # Output: 1

In this case:

  • The count of "hello" (lowercase) returns 1, while the uppercase "Hello" is not counted, demonstrating that str.count() is case-sensitive.

Example 4: Counting a substring not present

# Example 4: Substring not present my_string = "Hello, world!" count = my_string.count("Python") print(count) # Output: 0

Here:

  • The substring "Python" is not found in the original string, so the count returns 0.

Key Points:

  • str.count() returns the number of non-overlapping occurrences of the specified substring.
  • It is case-sensitive, meaning that different cases (uppercase vs. lowercase) are treated as different characters.
  • If the substring is not found, it returns 0.
  • You can specify optional start and end parameters to limit the search range within the string.
  • The function does not modify the original string.

Example 5: Counting overlapping substrings

If you want to count overlapping occurrences, you'll need a different approach, as str.count() does not count overlapping substrings.

# Example 5: Counting overlapping substrings (manual approach) my_string = "aaa" substring = "aa" # Using a loop to count overlapping occurrences count = 0 start = 0 while start < len(my_string): start = my_string.find(substring, start) if start == -1: # No more occurrences break count += 1 start += 1 # Move to the next character to count overlapping print(count) # Output: 2

In this example:

  • The loop counts overlapping occurrences of "aa" in the string "aaa" and outputs 2.