- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count words in a sentence in Python program
In this article, we will learn about the solution to the problem statement given below.
Problem statement − We are given a string we need to count the number of words in the string
Approach 1 − Using split() function
The split() function breaks the string into a list iterable with space as a delimiter. if the split() function is used without specifying the delimiter space is allocated as a default delimiter.
Example
test_string = "Tutorials point is a learning platform" #original string print ("The original string is : " + test_string) # using split() function res = len(test_string.split()) # total no of words print ("The number of words in string are : " + str(res))
Output
The original string is : Tutorials point is a learning platform The number of words in string are : 6
Approach 2 − Using regex module
Here findall() function is used to count the number of words in the sentence available in a regex module.
Example
import re test_string = "Tutorials point is a learning platform" # original string print ("The original string is : " + test_string) # using regex (findall()) function res = len(re.findall(r'\w+', test_string)) # total no of words print ("The number of words in string are : " + str(res))
Output
The original string is: Tutorials point is a learning platform The number of words in string is: 6
Approach 3 − Using sum()+ strip()+ split() function
Here, we first check all the words in the given sentence and add them using the sum() function.
Example
import string test_string = "Tutorials point is a learning platform" # printing original string print ("The original string is: " + test_string) # using sum() + strip() + split() function res = sum([i.strip(string.punctuation).isalpha() for i in test_string.split()]) # no of words print ("The number of words in string are : " + str(res))
Output
The original string is : Tutorials point is a learning platform The number of words in string are : 6
All the variables are declared in the local scope (Also Read: Local and Global Variables) and their references are seen in the figure above.
Conclusion
In this article, we have learned how to count the number of words in the sentence.