Count Words in String in Python
Count the number of words in a sentence.
BeginnerString ProgramsExample 20 of 25
count-words-in-string.py
Run in browser1# 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.