Computer >> Computer tutorials >  >> Programming >> Python

Python program to count words in a sentence


In this article, we will learn about the solution and approach to solve the given problem statement.

Problem statement

We are given a sentence, we need to count the number of words in the sentence

Here we will be discussing two approaches −

Approach 1 − Using split() function

Example

test_string = "Tutorials point "
res = len(test_string.split())
print ("The number of words in string are : " + str(res))

Output

The number of words in string are : 2

Approach 2 − Using strip() & isalpha() function

Example

import string
test_string = "Tutorials point "
res = sum([i.strip(string.punctuation).isalpha() for i in test_string.split()])
print ("The number of words in string are : " + str(res))

Output

The number of words in string are : 2

Conclusion

In this article, we learnt about the approach to count words in a sentence.