Count Words
Count whitespace-separated words with split and len. Students handle repeated spaces and tabs and distinguish token counting from a language-aware word parser.
1# Take string input2s = input("Enter a string: ")34# Count words5words = s.split()6count = len(words)78print(f"Number of words: {count}")
Output
Enter a string: Hello World Programming Number of words: 3
In this one
- Split whitespace runs
- Count tokens
- Handle empty text
How it works
- 1
Read the full response.
- 2
Call split without arguments.
- 3
Print the length of its token list.
Edge cases
What does whitespace-only input count as?
What does whitespace-only input count as?
Zero words.
Do repeated spaces create empty words?
Do repeated spaces create empty words?
No. split without arguments collapses whitespace runs.
What's going on
s.split() without an argument separates runs of whitespace and discards empty pieces. len then counts the resulting tokens.
For two spaces around red and blue, there are still two words. Tabs also separate tokens. Punctuation remains attached to a token, so hello, is one token rather than a cleaned dictionary word. The original string is not modified.
What does whitespace-only input count as? Zero words.
Do repeated spaces create empty words? No. split without arguments collapses whitespace runs.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Which value is measured by len?
Pick an answer to check it.
Question 2
What does whitespace-only input count as?
Pick an answer to check it.
Questions people ask
What does whitespace-only input count as?
Zero words.
Do repeated spaces create empty words?
No. split without arguments collapses whitespace runs.
Which value is measured by len?
The list returned by split.
๐Related Content
- ๐
Phase 5 - Learn Concepts
Review Phase 5 concepts and explanations
- ๐
Phase 5 - Quiz
Test your Phase 5 understanding with quiz questions
- ๐ป
Phase 5 - All Practice Problems
Explore all practice problems for Phase 5
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum