python count word occurrences in string code example
Example 1: Python Program to Count the Occurrences of a Word in a Text File
#get file object reference to the file
file = open("C:\workspace\python\data.txt", "r")
#read content of file to string
data = file.read()
#get number of occurrences of the substring in the string
occurrences = data.count("python")
print('Number of occurrences of the word :', occurrences)
Example 2: count in python string
string.count(substring, start, end)
# Start and end is optional
Example 3: string count substring occurences pytohn
string.count(substring, [start_index], [end_index])
Example 4: python count character occurrences
str1.count("a")
Example 5: how to count the occurrence of a word in string python
# define string
string = "Python is awesome, isn't it?"
substring = "is"
count = string.count(substring)
# print count
print("The count is:", count)