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.

Easy Python 3.9+ Aug 9, 2026 Strings & text 14 views 0 copies

Python code

9 lines
Python 3.9+
def 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

stdout
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

  1. Use `len(re.findall(r'\b\w+\b', text))` for a regex-based approach that excludes standalone punctuation
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.