Count Words in String in Python
Count the number of words in a sentence.
BeginnerString ProgramsExample 20 of 25
count-words-in-string.py
1# Program to count words in a sentence23sentence = input("Enter a sentence: ")45words = sentence.split()67print("Number of words:", len(words))
Output
Enter a sentence: count the words here Number of words: 4
What's going on
We split on whitespace and use len(words) to count words.
After this program
If the idea is still fuzzy, read Day 4: Strings and String Methods in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 string programs, or see every topic on Python exercises.