Python – Count Words in String

email me

Using Split

sentence = "How many words are in this sentence"
result = len(sentence.split())
print ("Number of words: " + str(result))

 

Using Regex

import re
sentence = "How many words are in this sentence"
result = len(re.findall(r'\w+', sentence))
print ("Number of words: " + str(result))

 

Notes

str.split

re.split