In this article, you will learn all about the Python string count() method. Python string count function is very useful to find the number of occurrences of a substring in a given string. In the previous tutorial, we have seen all about the Python string center() method.
Headings of Contents
Python String count() Method
In Python, the string count function is a built-in function that is only used with python string.
Python string count() function is used to return the number of occurrences of a substring in a specific range.
Syntax:
The syntax of string count() method is:
string.count(substring, start=..., end=....)
Parameter:
The Python string count function take three parameters: substring, start, end.
- substring – Required, Substring to be found.
- start – Optional, Position, where the search started.
- stop – Optional, Position where the search end.
Return Type:
The return type of Python string count function is the number of occurrences of the substring in the given string.
Let’s see an example for using python count() string function.
Python string count() method Example:
Here we will take various example to understand string count function in better way.
Example 1:
String count() method without start and end parameter.
str = "programming is best to learn coding"
print("String:- ", str)
str2 = str.count('programming')
print(str2)
Output
String:- programming is best to learn coding
1
Example 2:
str = "programming is best to learn to coding"
print("String:- ", str)
str2 = str.count('best', 14)
print(str2)
Output
String:- programming is best to learn to code
1
Example 3:
String count() method without start parameter and end parameter.
str = "programming is best to learn coding"
print("String:- ", str)
str2 = str.count('best', 14, 25)
print(str2)
Output
String:- programming is best to learn to code
1
Conclusion:
In this tutorial, you have learned all about the Python string count() method to count the number of occurrences of a substring in a given string. string count() method is a built-in string method, That means you can use the count() method only with string.
I hope this article will help you. if you like this article, please comment and share it with your friends who want to learn Programming.
For More Information:- Click Here