How to Count Words in a String in Python
Split a paragraph on whitespace and return the number of words using Python's built-in string methods.
Python code
9 linesdef count_words(paragraph: str) -> int:
words = paragraph.split()
return len(words)
if __name__ == "__main__":
paragraph = "The quick brown fox jumps over the lazy dog."
result = count_words(paragraph)
print(f"Word count: {result}")
Output
Word count: 9
How it works
The split() method called with no arguments splits the string on any sequence of whitespace characters (spaces, tabs, newlines) and returns a list of substrings. len() then counts the number of items in that list, which equals the number of words. This approach handles multiple consecutive spaces and newlines gracefully, unlike splitting on a single space character. The function uses type hints for clarity and the if __name__ == "__main__" block ensures the test code only runs when the script is executed directly.
Common mistakes
- Using `split(' ')` instead of `split()`, which creates empty strings with multiple spaces
- Forgetting that `split()` also splits on tabs and newlines, not just spaces
- Counting punctuation like periods as part of words when expecting different results
Variations
- Use `len(re.findall(r'\b\w+\b', text))` for a regex-based approach that excludes standalone punctuation
- Use `sum(1 for token in text.split())` for a more explicit counting loop
Real-world use cases
- Checking article word counts before publishing content to meet editorial guidelines.
- Estimating reading time for blog posts by dividing word count by average reading speed.
- Validating text input lengths, such as ensuring user-generated content stays within limits.
Sponsored
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.