Count Words in a Sentence

Easy ⏱ 8 min 85% acceptance ★★★★☆ 4.3
Write count_words(s) that returns the number of words in s, where words are separated by any amount of whitespace (spaces, tabs, or multiple spaces in a row).

Examples

Example 1
Input
s = '  Hello   world  '
Output
2
Explanation

Leading/trailing and repeated whitespace are ignored.

Example 2
Input
s = ''
Output
0
Explanation

An empty or whitespace-only string has zero words.

Constraints

  • 0 <= len(s) <= 10^4

Topics

Stringssplit

Companies

RazorpayPayPal

Hints

Hint 1

`s.split()` with no arguments already handles arbitrary whitespace runs and empty strings.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.