Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

1 Answer
Chandu yadav

Lets suppose we have a ‘string’ and the ‘word’ and we need to find the count of occurence of this word in our string using python. This is what we are going to do in this section, count the number of word in a given string and print it.

Count the number of words in a given string

Method 1: Using for loop

#Method 1: Using for loop

test_stirng = input("String to search is : ")
total = 1

for i in range(len(test_stirng)):
   if(test_stirng[i] == ' ' or test_stirng == '\n' or test_stirng == '\t'):
      total = total + 1

print("Total Number of Words in our input string is: ", total)

Result

String to search is : Python is a high level language. Python is interpreted language. Python is general-purpose programming language
Total Number of Words in our input string is: 16

#Method 2: Using while loop

test_stirng = input("String to search is : ")
total = 1
i = 0
while(i < len(test_stirng)):
   if(test_stirng[i] == ' ' or test_stirng == '\n' or test_stirng == '\t'):
      total = total + 1
   i +=1

print("Total Number of Words in our input string is: ", total)

Result

String to search is : Python is a high level language. Python is interpreted language. Python is general-purpose programming language
Total Number of Words in our input string is: 16

#Method 3: Using function

def Count_words(test_string):
   word_count = 1
   for i in range(len(test_string)):
      if(test_string[i] == ' ' or test_string == '\n' or test_string == '\t'):
         word_count += 1
   return word_count
test_string = input("String to search is :")
total = Count_words(test_string)
print("Total Number of Words in our input string is: ", total)

Result

String to search is :Python is a high level language. Python is interpreted language. Python is general-purpose programming language
Total Number of Words in our input string is: 16

Above are couple of other ways too, to find the number of words in the string entered by the user.

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.