count(): Number of presence of a string

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

Example: Counting Substrings Across Multiple Lines

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

Use Case: Case-Insensitive Count with Regular Expressions

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

Advanced Example: Counting Words in a File

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.

Example: Counting Character Sequences with Optional Start and End

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

All String methods

Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer