Count number of words in a string in python

Last updated 2 months, 1 week ago | 91 views 75     5

Tags:- Python

Python | Program to count the number of words in a string

split() and len() method is used to get the number of words in a string. The split() method split a string into a list where each word is a list item and the len() method returns the number of items in a list.

# initializing string
sentence = "Program to count the number of words in a sentence"
  
# printing original string 
print ("Original string: " +  sentence) 
  
# count words in string 
count = len(sentence.split()) 
  
# printing result 
print ("Number of words in the string are: " +  str(count)) 

Output:

Original string: Program to count the number of words in a sentence
Number of words in the string are: 10