- Python Basic Programs
- Python Program Examples
- Python Print Hello World
- Python Get Input from User
- Python Add Two Numbers
- Add Subtract Multiply Divide
- Python Check Even or Odd
- Python Check Prime or Not
- Python Check Alphabet or Not
- Python Check Vowel or Not
- Python Check Leap Year or Not
- Check Reverse equal Original
- Check Positive Negative Zero
- Python Check Armstrong or Not
- Python Check Palindrome or Not
- Python Check Perfect Number
- Python Find Reverse of Number
- Python Count Digits in Number
- Python Add Digits of Number
- Sum of First and Last Digits
- Python Product of Mid Digits
- Sum of Squares of Digits
- Interchange Digits of Number
- Python Sum of n Numbers
- Python Print ASCII Values
- Python Swap Two Numbers
- Python Swap Two Variables
- Python Fahrenheit to Celsius
- Python Celsius to Fahrenheit
- Python Display Calendar
- Python Days into Years, Weeks
- Find Largest of Two Number
- Find Largest of Three Number
- Python Print Fibonacci Series
- Generate Armstrong Numbers
- Python Make Simple Calculator
- Python Add Binary Numbers
- Binary Number Multiplication
- Python Mathematical Programs
- Find Sum of Natural Numbers
- Find Average of n Numbers
- Python Print Multiplication Table
- Print Table using Recursion
- Python Find Average Percentage
- Python Find Grade of Student
- Find Square Root of Number
- Python Print Prime Numbers
- Find Numbers Divisible by
- Python Find Factors of Number
- Python Find Factorial of a Number
- Python Find HCF & LCM
- Python Kilometres to Miles
- Python Find Area of Square
- Python Find Area of Rectangle
- Python Find Area of Triangle
- Python Find Area of Circle
- Python Find Perimeter of Square
- Find Perimeter of Rectangle
- Python Find Perimeter of Triangle
- Find Circumference of Circle
- Python Simple Interest
- Python Solve Quadratic Equation
- Python Different Set of Operations
- Python Display Powers of 2
- Python Find nCr & nPr
- Python Pattern Programs
- Python Print Pattern Programs
- Python Print Diamond Pattern
- Python Print Floyd's Triangle
- Python Print Pascal's Triangle
- Python List Programs
- Python Count Even/Odd in List
- Python Positive/Negative in List
- Python Even Numbers in List
- Python Odd Numbers in List
- Python Sum of Elements in List
- Sum of Odd/Even Numbers
- Python Element at Even Position
- Python Element at Odd Position
- Python Search Element in List
- Python Largest Number in List
- Python Smallest Number in List
- Python Second Largest in List
- Python Second Smallest in List
- Python Insert Element in List
- Python Delete Element from List
- Python Multiply Numbers in List
- Swap Two Elements in List
- Python 1D Array Program
- Python Linear Search
- Python Binary Search
- Python Insertion Sort
- Python Bubble Sort
- Python Selection Sort
- Remove Duplicates from List
- Python Reverse a List
- Python Merge Two List
- Python Copy a List
- Python Conversion Programs
- Python Decimal to Binary
- Python Decimal to Octal
- Python Decimal to Hexadecimal
- Python Binary to Decimal
- Python Binary to Octal
- Python Binary to Hexadecimal
- Python Octal to Decimal
- Python Octal to Binary
- Python Octal to Hexadecimal
- Python Hexadecimal to Decimal
- Python Hexadecimal to Binary
- Python Hexadecimal to Octal
- Python Matrix Programs
- Python Add Two Matrices
- Python Subtract Two Matrices
- Python Transpose Matrix
- Python Multiply Matrices
- Python String Programs
- Python Print String
- Python Find Length of String
- Python Compare Two Strings
- Python Copy String
- Python Concatenate String
- Python Reverse a String
- Python Swap Two Strings
- Python Uppercase to Lowercase
- Python Lowercase to Uppercase
- Python Check Substring in String
- Python Count Character in String
- Count Repeated Characters
- Python Count Word in Sentence
- Python Count Each Vowels
- Python Capitalize Character
- Python Capitalize Word in String
- Python Smallest/Largest Word
- Remove Spaces from String
- Remove Duplicate Character
- Remove Vowels from String
- Remove Punctuation from String
- Python Remove Word in String
- Python Remove Duplicate Words
- WhiteSpace to Hyphens
- Replace Vowels with Character
- Replace Character in String
- Python Sort String in Alphabetical
- Sort Word in Alphabetical Order
- Extract Number from String
- Python Check Anagram Strings
- Python File Programs
- Python Read a File
- Python Write to File
- Python Append Text to File
- Python Copy Files
- Python Merge Two Files
- Python Counts Characters in File
- Python Count Words in File
- Python File Content in Reverse
- Python Lines Contains String
- Python Delete Line from File
- Python Capitalize Word in File
- Python Replace Text in File
- Replace Specific Line in File
- Python Find Size of File
- Python List Files in Directory
- Python Delete Files
- Python Misc Programs
- Python Reverse a Tuple
- Python Merge Two Dictionary
- Python bytes to String
- Python bytearray to String
- Generate Random Numbers
- Python Print Address of Variable
- Python Print Date and Time
- Python Get IP Address
- Python Shutdown/Restart PC
- Python Tutorial
- Python Tutorial
Python Program to Count Words in a String
This article is created to cover some programs in Python, that count and prints total number of words available in a string entered by user at run-time. Here are the list of approaches used to do the job:
- Count Words in String using for Loop
- Using len() and split() Methods
- Using user-defined Function
- Using Class
Count Words in String using for Loop
To count total number of words present in a given string or sentence in Python, you have to ask from user to enter a string, then count and print total words available in the string like shown in the program given below:
print("Enter the String: ") text = input() chk = 0 countWord = 0 textLen = len(text) for i in range(textLen): if text[i]==' ': if chk!=0: countWord = countWord+1 chk = 0 else: chk = chk+1 if chk!=0: countWord = countWord+1 print("\nNumber of Word(s): ") print(countWord)
Here is its sample run:
Now supply the input say welcome to fresherearth as string and press ENTER
key to count and
print the total number of words available in the given string:
Here is another sample run with following user input:
this is fresherearth
That is, 4 spaces then this, 3 spaces then is, and a single space then fresherearth:
Note - The len() method returns length of string passed as its argument.
In above program, the following code (for loop's code):
for i in range(textLen):
is used to execute all statements available in its body, textLen number of times with value of i from 0 to textLen-1. For example, if textLen's value is 5, then this loop gets evaluated five times with value of i from 0 to 4
The dry run of above program with string input welcome to fresherearth, as provided in first sample run, goes like:
- Initial values, chk=0, countWord=0, text="welcome to fresherearth" (entered by user)
- Now the following statement:
textLen = len(text)
initializes the length of string stored in text to textLen. So textLen=23 - Now the execution of for loop begins. Initially i=0, since 0 is less than 23, therefore condition evaluates to be true, so program flow goes inside the loop
- Inside the loop, the condition (of if) text[i]==' ' or text[0]==' ' or 'w'==' ' evaluates to be false, therefore program flow does not goes in its body
- Rather it goes to else's body and chk+1 or 0+1 or 1 gets initialized to chk. So chk=1
- Now the value of i gets incremented. So i=1, since 1 is less than 23, therefore program flow again goes inside the loop
- Again the condition (of if) text[i]==' ' or text[1]==' ' or 'e'==' ' evaluates to be false, therefore chk+1 or 1+1 gets initialized to chk
- Now i=2, since 2 is less than 23, therefore third time also, program flow goes inside the for loop's body
- This process continues, until the condition evaluates to be false, or until the value of i becomes equal to 23 (length of string)
- Inside the loop, when character at any ith index gets equal to a space, then I've checked whether the value of chk is not equal to 0 or not, if condition evaluates to be true, then only the variable countWord gets incremented by 1
- In this way, after exiting from the loop, I've a variable named countWord that holds the total number of words
- After exiting from the loop, another condition applied to check and increment the value of countWord for last word. Because in general, last word in any sentence or string does not contains any space after it.
- Now print the value of countWord as number of words available in the string entered by user.
Count Words in String using len() and split()
This program also count and prints total words available in a string, but using predefined function named split(). The split() method splits string into words. Let's have a look at the program first:
print(end="Enter the String: ") text = input() wordLen = len(text.split()) print("\nNumber of Word(s): " + str(wordLen))
Here is its sample run with user input, This is Python Program:
From above program, the following code (statement):
wordLen = len(text.split())
can also be replaced with the block of code given below, to make it more understandable:
wordlist = text.split() wordLen = len(wordlist)
that is, the first statement creates a list of words using split(). And the second statement initializes the length of list named wordlist using len() method. Length of list means, total number of elements available in the list. Elements of list here are words
Count Words in a String using Function
This program uses a user-defined function named CountWords(), that receives a string as its argument and returns its length like done in previous program. The only difference is, the main code gets wrapped into a user-defined function.
def CountWords(s): wlist = s.split() wtot = len(wlist) return wtot print("Enter the String: ", end="") text = input() wordLen = CountWords(text) print("\nNumber of Word(s):", wordLen)
Produces same output as of previous program.
Count Words in a String using Class
This is the last program created using a class named fresherearth. Class is an object-oriented feature of Python. Function inside a class, is called as its member function.
class fresherearth: def CountWords(self, s): wrds = s.split() totwrds = len(wrds) return totwrds print("Enter the String: ", end="") text = input() ob = fresherearth() textlen = ob.CountWords(text) print("\nNumber of Word(s):", textlen)
To access member function of a class, an object of that class is required. Therefore an object named ob of class fresherearth is created, and using dot (.) operator, I've accessed its member function through its object like shown in above program.
Same Program in Other Languages
« Previous Program Next Program »