Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

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.

BeginnerPhase 5 - Category 1: Basic String HandlingExample 7 of 10
count-words.py
1# Take string input
2s = input("Enter a string: ")
3
4# Count words
5words = s.split()
6count = len(words)
7
8print(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. 1

    Read the full response.

  2. 2

    Call split without arguments.

  3. 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.