This Python String function counts and return how many times the substring occurred in the specified start and end position. Here start, and end index positions are optional. In this section, we discuss how to write the String count Function.
The syntax of the String Count function is
String_Value.count(Substring, Starting_Position, Ending_Position)
- Substring: String on which you want to use.
- Starting_Position: This is an optional parameter. If you want to specify the starting point (starting index position), then specify it here. If you omit this parameter, then the function considers Zero as a starting position.
- Ending_Position (Optional): If you want to specify the endpoint (Ending index position), then specify it here. If you omit this parameter, it considers the highest number.
Python String count Example
The following set of examples helps you understand the String count Function.
Str1 = 'We are abc working at abc company with abc Employee'; Str2 = Str1.count('abc') print('First Output of this method is = ', Str2) # Performing directly Str3 = 'Find Tutorial at Tutorial Gateway'.count('Tutorial') print('Second Output of a method is = ', Str3) # Using First Index Str5 = Str1.count('abc', 12) print('Third Output of a method is = ', Str5) # Using First & Second Str6 = Str1.count('abc', 12, len(Str1) -1) print('Fourth Output of a method is = ', Str6) # Using First & Second Str7 = Str1.count('abc', 12, 21) print('Fifth Output of a method is = ', Str7)
First, we declared the String variable Str1 and assigned data.
Str1 = 'We are abc working at abc company with abc Employee';
The following statement counts the number of times the substring ‘abc’ is repeated inside the Str1 using this function and prints the output.
Str2 = Str1.count('abc')
It also allows us to use the Starting index position. By specifying it, we can increase the String function performance.
Str5 = Str1.count('abc', 12)
It allows us to use Starting and ending indices. By specifying the starting and ending, we can increase performance. The below Python statement returns the number of occurrences from index position 12 and up to the end.
Str6 = Str1.count('abc', 12, len(Str1) -1)
It returns zero because this function starts looking from 12 (means the first abc skipped) and ends at index position 21. As we all know, the second abc is at 22. It means there are no substrings to tally between those.
Str7 = Str1.count('abc', 12, 21)