Editor

Python Program to Count the Words in a String

Beginner · Strings

A word is a group of characters with spaces on either side, so "Python is easy" has three words. This program splits a sentence into a list of words and counts the list.

Program

count_words_in_string.py
text = "Python is easy to learn and fun to use" # or: text = input("Enter a sentence: ")
words = text.split() # break the sentence into a list of words
print("Sentence:", text)
print("Words:", words)
print("Number of words:", len(words))
Output
Sentence: Python is easy to learn and fun to use
Words: ['Python', 'is', 'easy', 'to', 'learn', 'and', 'fun', 'to', 'use']
Number of words: 9

How it works

  1. text.split() with no argument cuts the string wherever there is a space, tab or new line, and returns the pieces as a list.
  2. It treats several spaces in a row as one gap and ignores spaces at the start and end, so " hi there " still gives two words.
  3. len(words) counts the items in the list, which is the number of words.
  4. Punctuation stays attached to its word, so "fun!" counts as one word, which is usually what you want.

Other ways to write it

Without using split()

Without using split()
text = " Learning Python is fun "
count = 0
in_word = False
for ch in text:
if ch != " " and not in_word:
count += 1 # a new word starts here
in_word = True
elif ch == " ":
in_word = False # a space ends the current word
print(f'Sentence: "{text}"')
print("Number of words:", count)
Output
Sentence: "  Learning   Python is fun  "
Number of words: 4

The loop counts the moments a word starts: a character that is not a space, coming right after a space or at the very beginning. Counting the spaces and adding 1 would give the wrong answer here because of the extra spaces.

Count the words in several sentences

Count the words in several sentences
def word_count(sentence):
return len(sentence.split())
sentences = ["Hello world", "Practice makes a man perfect", "", "Python"]
for s in sentences:
count = word_count(s)
print(f'"{s}" has', count, "word" if count == 1 else "words")
Output
"Hello world" has 2 words
"Practice makes a man perfect" has 5 words
"" has 0 words
"Python" has 1 word

A function lets you count many sentences with one line each, and an empty string correctly gives 0 words.

Try it yourself

Count only the words longer than three letters by looping over words and checking len(word) > 3.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises