Python string Method - count()

www.ig‮i‬ftidea.com

The count() method in Python strings returns the number of occurrences of a specified substring within the string. The substring is specified as an argument to the count() method.

The syntax for the count() method is as follows:

string.count(substring, start, end)

Here, string is the string that we want to search, substring is the substring that we want to count, start is the starting index for the search (optional, default is 0), and end is the ending index for the search (optional, default is the end of the string).

Example:

# Defining a string
my_string = "hello world"

# Using the count() method
count = my_string.count('l')

print(count)   # Output: 3

In the above example, the count() method is used to count the number of occurrences of the substring 'l' within the string my_string. Since there are 3 occurrences of the substring 'l' in my_string, the variable count is assigned the value 3, which is printed using the print() function. Note that the count() method is case-sensitive, so it will not count occurrences of 'L' or 'l' if they are in different case.