Counting occurrences of a substring within a string is a common string manipulation task. Python provides a built-in method called count() to count the number of occurrences of a substring within a given string.
The count() method takes one argument which is the substring to search for, and it returns an integer representing the number of occurrences of the substring within the string. Here is an example:
string = "She sells seashells by the seashore."substring = "se"count = string.count(substring)print(count) # Output: 4 |
In this example, the count() method is used to count the number of occurrences of the substring "se" within the string "She sells seashells by the seashore.". The method returns the value 4, which is the number of times the substring appears in the string.
You can also use the count() method with overlapping substrings. For example:
string = "aaaaaa"substring = "aa"count = string.count(substring)print(count) # Output: 5 |
In this example, the count() method is used to count the number of occurrences of the substring "aa" within the string "aaaaaa". Even though the substring overlaps itself, the method correctly counts all 5 occurrences.
The count() method is a simple but powerful way to count occurrences of a substring within a string. You can use it to perform various string manipulation tasks such as searching for specific words or patterns, counting the frequency of letters or characters, and more.