
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python Program to Count Words in a Given String
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