Python program to count the number of word in a given string


Program:



#function to Count number of times s1 occurs in s
def countword(s,s1):
#intialize all variables to zero
 n=0                     
 count=0
#x is same as length os s1
 x=len(s1)               
 while(n<(len(s)-2)):   
# count how many times s occurs in s1 using while loop
    if(s[n:n+x]==s1):   
#if string is same as the s1 the incriment count
        count=count+1
    n=n+1
 print("Number of times "+s1+" occurs is: "+str(count)) #at the end print result

#main program calling function wordcount
str1=raw_input("Enter the String: ")
str2=raw_input("Enter the word To be counted: ")
countword(str1,str2)

        


Note : Please Do not change indentation while executing 


Output:



 

Comments