Python String count() function returns the number of occurrences of a substring in the given string.
Python String count()
The count() function syntax is:
str.count(sub[, start[, end]])
sub is the substring to find in the given string.
start is an optional argument. It specifies the starting index position from where the substring is looked for. Its default value is 0.
end is an optional argument. It specifies the ending index position in the specified string. Its default value is the length of the string.
Let’s look at a simple example of string count() function.
s="I like Python programming. Python is Awesome!"
print(f'Number of occurrence of "Python" in String = {s.count("Python")}')
print(f'Number of occurrence of "Python" in String between index 0 to 20 = {s.count("Python", 0, 20)}')
Output:
Number of occurrence of "Python" in String = 2
Number of occurrence of "Python" in String between index 0 to 20 = 1
Recommended Reading: Python f-strings
Let’s look at another example where the user will enter the string and substring and we will print the count of occurrences using count() function.
s = input('Please enter a string:n')
sub = input('Please enter a sub-string:n')
print(f'Number of occurrence of "{sub}" in the "{s}" is {s.count(sub)}')
Output:
Please enter a string:
a,e,i,o,u
Please enter a sub-string:
,
Number of occurrence of "," in the "a,e,i,o,u" is 4
Please enter a string:
Hello World from Python Tutorials from JournalDev
Please enter a sub-string:
from
Number of occurrence of "from" in the "Hello World from Python Tutorials from JournalDev" is 2
Reference: API Doc