my_str="Welcome to plus2net.com"
print(my_str.count('co')) # Output is 2
print(my_str.count('co',4)) # Output is 1
print(my_str.count('co',4,18)) # Output is 0
print(my_str.count('o',4,9)) # Output is 1
print(my_str.count('o',4,10)) # Output is 2
Note : In last line in above code the char o is at 4th and 94th position.
my_str.count(search_string,start,end))
search_string
: String to be searched for matching inside main string. start
: Optional , search can be started from this position end
: Optional , search can be ended just before this position.
Using a list
my_list=['one','two','three']
print(my_list.count('two')) # Output is 1
We can use `count()` to identify substrings across multiple lines. This is particularly useful when processing multi-line text files or user inputs.
text = """Welcome to plus2net.com
Visit us for Python tutorials.
Enjoy your learning journey at plus2net.com!"""
count = text.count("plus2net.com")
print(count)
2
To perform a case-insensitive count, we can use the `re` module instead of `count()`. This is helpful when the exact match case isn't important.
import re
text = "Python is fun. PYTHON is versatile. python is popular."
count = len(re.findall(r'python', text, re.IGNORECASE))
print(count)
Output
3
Regular use of `count()` can help in text analysis, such as determining word frequencies in a file.
file_name = 'example.txt'
with open(file_name, 'r') as file:
content = file.read()
word_count = content.count("Python")
print(f"'Python' appears {word_count} times in the file.")
'Python' appears 5 times in the file.
We can specify start and end parameters to limit the search to specific sections of a string, which helps when analyzing parts of data.
my_str = "Find your way in Python programming"
print(my_str.count("y", 5, 20))
Output
3