Python Basics

Python Count the number of occurrence of a sub string in a string?

Lets see how to find out the number of occurrence of a sub string in a string.

Example:

sentence=”This is a lovely day and this day could be your best day, if you smile”

Count how many times the word ‘day’ (substring) is appearing in the above sentence (string)

Solution 1

sentence=”This is a lovely day and this day could be your best day, if you smile”

daycount=sentence.split(‘day’)

print(‘The substring day is appearing : ‘+len(daycount)-1)

Output: The substring day is appearing : 3

In the above code, we have splitted the sentence with the substring ‘day’ and returns list. If we deduct one from the number of elements present in the list, we get the number of substring present in the string. If there are no match found then it would return 1 and after deducting one from list element count, we get zero. So if no substring is present then it would print 0.

Solution 2

Python has in built function ‘count’ that counts the number of substring occurrence in a string.

Lets take above example

sentence=”This is a lovely day and this day could be your best day, if you smile”

print((‘The substring day is appearing : ‘+ sentence.count(‘day’))

Output: The substring day is appearing : 3

Solution 3

By using regular expression we can also count the number of occurrence of a character in a string.

import re

sentence=”This is a lovely day and this day could be your best day, if you smile”

substringcount=re.compile(‘day’).findAll(sentence)

print((‘The substring day is appearing : ‘+ len(substringcount))

Output: The substring day is appearing : 3