Count of a given substring from a string in Python
In Python, you can use the count() method to find the number of occurrences of a substring in a string. Here is an example:
my_string = "johny , johny ! yes , appa!"
substring = "johny"
count = my_string.count(substring)
print(count)
//Output: 2
In this example, the count() method is called on my_string with the argument substring, which is "johny". The count() method returns the number of occurrences of the substring in the string, which in this case is 2. So the output will be 2.
Using Python Regular Expression
You can also use python's re library to achieve the same results:
import re
my_string = "johny , johny ! yes , appa!"
substring = "Hello"
count = len(re.findall(substring, my_string))
print(count)
//Output: 2
In this example, findall() returns all the non-overlapping matches of the substring in the string, then we use the len() function to count the number of matches.
Please note that count() is case sensitive, meaning it will return the count of exact matches of the substring, if you want to find the count of substring regardless of the case, you can convert the string and substring to lower/upper case before using count() method.
Python re module

The re module in Python is a built-in library for working with regular expressions. Regular expressions are a powerful tool for matching patterns in text, and the re module provides a set of functions for working with them in Python.
Some common uses of the re module include:
- search(): searches for a match anywhere in the string.
- split(): splits the string by the occurrences of the pattern.
- match(): checks for a match only at the beginning of the string.
- sub(): replaces all occurrences of the pattern in the string with a replacement string.
- findall(): returns all non-overlapping matches of the pattern in the string as a list of strings.
- finditer(): returns an iterator yielding match objects for all non-overlapping matches of the pattern in the string.
Related Topics
- Print the following pattern using python
- Python Program to Check Leap Year
- Remove first n characters from a string | Python
- Check if the first and last number of a list is the same | Python
- Remove last element from list in Python
- How to Use Modulo Operator in Python
- Enumerate() in Python
- Writing to a File using Python's print() Function
- How to read csv file in Python
- Dictionary Comprehension in Python
- How to Convert List to String in Python
- How to convert int to string in Python
- Random Float numbers in Python