Count Words in String
Count the number of words in a sentence.
BeginnerTopic: String Programs
Python Count Words in String Program
This program helps you to learn the fundamental structure and syntax of Python programming.
# Program to count words in a sentence
sentence = input("Enter a sentence: ")
words = sentence.split()
print("Number of words:", len(words))Output
Enter a sentence: count the words here Number of words: 4
Understanding Count Words in String
We split on whitespace and use len(words) to count words.
Note: To write and run Python programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Python Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Python programs.