Python Word Count Program: Count Words in a String
len(text.split()).A word counter is one of the most useful small text programs. It powers character limits, reading-time estimates and the simple statistics you see in editors. In Python the whole job is usually one line, because str.split() with no arguments already understands runs of spaces, tabs and newlines.
This page covers the one-line total, a version that counts how often each word appears, and the edge cases that surprise beginners: extra spaces, punctuation and empty text.
| Input | A string of text |
|---|---|
| Output | The number of words, or a mapping of word to count |
| Approach | Split on whitespace, then use len() or count each word |
| Time complexity | O(n) for n characters |
Approach to count words step by step
- Call
text.split()with no argument. It splits on any run of whitespace and ignores leading and trailing spaces. - Use
len()on the resulting list to get the total number of words. - For per-word counts, lowercase the words, loop over them and add one to a dictionary entry for each.
- Optionally strip punctuation so "fun." and "fun" count as the same word.
How the word count code works
" hello world ".split() returns ["hello", "world"]: the extra spaces vanish. That is why plain split() is better than split(" "), which would create empty strings for each extra space.
For frequencies, counts.get(word, 0) + 1 reads the current count (0 when the word is new) and stores it back plus one. This pattern avoids a KeyError; see dict.get().
text = " to be or not to be "
words = text.split()
print(words)
print(len(words))Handling punctuation and counting repeated words
Punctuation stays attached to words after split(), so "Python," and "Python" are different. A simple fix is word.strip(".,!?;:") on each word, using strip(). For serious text processing you would use a regular expression, covered in the regex lesson. To see the most common words, collections.Counter(words).most_common(3) does the counting and the ranking for you.
Examples you can run
Press Run, then edit the code and run it again.
Count the words in a sentence
split() with no argument handles extra spaces, tabs and newlines.
text = "Python is easy to learn\nand fun"
words = text.split()
print(words)
print("Word count:", len(words))Expected output['Python', 'is', 'easy', 'to', 'learn', 'and', 'fun']
Word count: 7
Count how often each word appears
Lowercase and strip punctuation, then build a dictionary of counts.
text = "The cat sat. The dog sat, too!"
counts = {}
for word in text.lower().split():
word = word.strip(".,!?")
counts[word] = counts.get(word, 0) + 1
print(counts)Expected output{'the': 2, 'cat': 1, 'sat': 2, 'dog': 1, 'too': 1}
Top words with Counter
most_common() returns the highest counts first.
from collections import Counter
text = "red blue red green blue red"
print(Counter(text.split()).most_common(2))Expected output[('red', 3), ('blue', 2)]
Edge case: empty and blank text
Blank text has no words, so the count is 0.
for text in ["", " ", "one"]:
print(len(text.split()))Expected output0
0
1
Interactive word counter
Read a line and report the number of words.
line = input("Enter some text: ")
print("Words:", len(line.split()))Expected outputEnter some text: the quick brown fox
Words: 4
Common mistakes
Splitting on a single space
✗ Wrong
text = "a b"
print(len(text.split(" ")))✓ Right
text = "a b"
print(len(text.split()))Call split() with no argument so any run of whitespace counts as one separator.
Counting characters instead of words
✗ Wrong
text = "hello world"
print(len(text))✓ Right
text = "hello world"
print(len(text.split()))Split the text into words first, then take the length of the list.
Python Word Count Program: Count Words in a String: questions people ask
How do I count words in a string in Python?
Use len(text.split()). With no argument, split() breaks the text on any whitespace and ignores extra spaces at the ends.
How do I count the occurrences of a specific word?
Split the text and use words.count("word"), or use Counter(words)["word"]. Lowercase everything first if capitalisation should not matter.
Does split() remove punctuation?
No. Punctuation stays attached to the neighbouring word, so strip it with strip() or use a regular expression when accuracy matters.
Keep learning
Step-by-step lessons:
Python StringsPython String MethodsPython Dictionaries
Related:
Python String split() MethodPython Program to Count Character Frequency in a StringHow to Split a String into Words in PythonHow to Count Occurrences in a List in Python
More in string programs:
Python Program to Check Palindrome (String and Number)Python Program to Count Vowels in a StringPython Anagram Program: Check if Two Strings Are AnagramsPython Program to Count Character Frequency in a String See all →