Get Word Count in a Sentence
Quick Overview
`split()` with no argument collapses runs of whitespace and ignores leading and trailing spaces. `split(" ")` does neither, so a double space yields an empty string in the result.
Deep Dive
1. The Challenge: Counting Words
Create a function count_words(txt) that takes a string of text and returns the total word count.
2. Why It Matters
Text analysis, document search indexing, and social media post validation rely on calculating word counts.
3. The Python Solution
Use the string .split() method to split text by spaces into a list of words, then measure length with len():
def count_words(txt):
words = txt.split()
return len(words)
# Testing our function
print(count_words("Just an example here")) # Output: 4
print(count_words("Is this easy?")) # Output: 3
print(count_words("Hello World")) # Output: 2
4. How .split() Handles Whitespace
Calling .split() without arguments automatically handles multiple consecutive spaces, tabs, and newlines cleanly without creating empty string items.
5. Common Mistakes
- Passing Explicit Space Parameter
txt.split(" "): Callingtxt.split(" ")fails when multiple spaces exist between words! Always calltxt.split()without arguments for general word tokenization.
6. Next Steps
Use txt.split() and len() for word counts. Next, let's find the minimum and maximum numbers in a list!
Next Up in Python Beginner Practice & Core Problem Solving
Return the Sum of Two Numbers
A function with no `return` hands back `None`, so a forgotten one surfaces as a `TypeError` at the call site rather than at the line that actually caused it.
Convert Minutes into Seconds
`minutes * 60` returns an `int` when given an `int`, while `/` always produces a float regardless of the operands. Multiplication preserves the type; division does not.
Calculate the Area of a Triangle
`base * height / 2` always yields a float in Python 3 because `/` never returns an int, even for whole numbers. `//` floors instead, which is almost never what an area wants.