How Can We Help?
In this tutorial, we will explain how to use Python string count() method with basic syntax by example for better understanding.
The String count() method is a built-in function in Python. It is counts how many times a given substring occurs in a string between the given start and end index.
Syntax:
<string_value/string_variable>.count(substring/substring_variable,start index, end index)
Input Parameters:
- string / String variable : The string that we want to counts how many times a given substring occurs in a string.
- Start : The start index that we need to check the substring value start counting from. this is an optional parameter.
- End : The end index that we need to end count the check of substring value. this is an optional parameter.
Python String Count Occurrences
We can count how many times a given substring occurs in a string by simply using the count(substring_value) method.
Example (1)
#Print the result of count() method
msg= 'welcome to python!'
substr='e'
print ('For string variable:',msg.count(substr, 5 , 14))
Output of example (1)
For string variable: 1
In the above example, substring “e” is present one time in between string index 5 to 14 of string variable msg ‘welcome to python!’ so the output is 1.
Example (2)
#Print the result of count() method
print('For string value:','parismumbai'.count('i'))
Output of example (2)
For string value: 2
In the above example, the string variable is ‘msg’, and the substring variable is ‘substr’. Substring ‘I’ is present two times in string ‘PARISMUMBAI’, so the output is 2.
In this tutorial, you have learned the string count() method in Python. What is it? And how to counts how many times a given substring occurs in a string between the given start and end index.
Hopefully, it was clear and concise.
If you have an inquiry or doubt, don’t hesitate to leave them in a comment. We are waiting for your valuable feedback.
Similar Python String Manipulation Methods:
- join() : It merges (concatenates) the sequence into a string.
- replace() : It replaces the old string value with a new string value.
- split() : It splits the string according to the passed delimiter string and returns the list of substrings.
- splitlines() : It splits the string at all newlines or the number of newlines and returns a list of each line with newlines removed.
- find() : It returns the index value of the string, where a given substring is found between the given start index and end index.
- rfind() : It works the same as the find() method but only searches from the backward in a string.
- index() : It works same like find() method only raises an exception if substring is not found in a string between given start and end index.
- rindex() : It works the same as the index() method but only searches from the backward in a string.
Related Articles
Python String – Mastering By Practical Examples (Comprehensive Guide)
Python tutorials list:
- Python tutorials list : access all python tutorials.