String count() Method in Python

String count() Method

The count() method in Python is used to count the occurrences of a substring within a given string. It scans the original string and returns the number of times the specified substring appears in it.Here's the syntax of the count() method:

string.count(substring, start, end)

Parameters:

  • substring: The substring you want to count occurrences of in the original string.
  • start (optional): The index from which the search for the substring begins. It is an optional parameter, and if not provided, the search starts from the beginning of the string.
  • end (optional): The index at which the search for the substring ends. It is an optional parameter, and if not provided, the search goes until the end of the string.

Example:

# Example string
original_string = "How much wood would a woodchuck chuck if a woodchuck could chuck wood?"

# Counting occurrences of the substring "wood" in the string
occurrences = original_string.count("wood")

print("Original String:", original_string)
print("Occurrences of 'wood':", occurrences)

Output:

Original String: How much wood would a woodchuck chuck if a woodchuck could chuck wood?
Occurrences of 'wood': 4

 

In this example, we used the count() method to count how many times the substring "wood" appears in the original string. The method returned 4, indicating that "wood" occurs four times in the string. You can also use the optional start and end parameters to search for the substring within specific portions of the original string if needed.