Python Program to Count the Words in a String
Beginner · Strings
A word is a group of characters with spaces on either side, so "Python is easy" has three words. This program splits a sentence into a list of words and counts the list.
Program
Sentence: Python is easy to learn and fun to use Words: ['Python', 'is', 'easy', 'to', 'learn', 'and', 'fun', 'to', 'use'] Number of words: 9
How it works
text.split()with no argument cuts the string wherever there is a space, tab or new line, and returns the pieces as a list.- It treats several spaces in a row as one gap and ignores spaces at the start and end, so
" hi there "still gives two words. len(words)counts the items in the list, which is the number of words.- Punctuation stays attached to its word, so "fun!" counts as one word, which is usually what you want.
Other ways to write it
Without using split()
Sentence: " Learning Python is fun " Number of words: 4
The loop counts the moments a word starts: a character that is not a space, coming right after a space or at the very beginning. Counting the spaces and adding 1 would give the wrong answer here because of the extra spaces.
Count the words in several sentences
"Hello world" has 2 words "Practice makes a man perfect" has 5 words "" has 0 words "Python" has 1 word
A function lets you count many sentences with one line each, and an empty string correctly gives 0 words.
Try it yourself
Count only the words longer than three letters by looping over words and checking len(word) > 3.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
- Count the Frequency of Words in a String
- Count Words in a Text File
- Find the Longest Word in a Sentence
- Count Vowels, Consonants, Uppercase and Lowercase Letters
- Check a Palindrome String
- Reverse a String
- Generate a Random Password
- Count the Frequency of Each Character in a String
- Remove Punctuation from a String
- Sort Words in Alphabetical Order
All Python programs · CBSE class 12 practical file · Python exercises