text.split() breaks a string into a list of words. len() of that list is the number of words.
The program
text = input("Enter a sentence: ") words = text.split() print(f"Words: {len(words)}") print(words)
Typed in this example: Python is a great language. Press Run to type your own.
Enter a sentence: Python is a great language Words: 5 ['Python', 'is', 'a', 'great', 'language']
How it works
- With no argument,
split()splits on any run of whitespace: spaces, tabs and new lines. Two or three spaces in a row count as one gap. - It also ignores spaces at the start and the end. An empty string, or a string of only spaces, gives an empty list, so the count is 0.
Do not use split(" ")
split(" ") splits on every single space. Two spaces in a row leave an empty string between them, and each empty string is counted as a word:
text = "Python is a great language" print(len(text.split())) print(len(text.split(" "))) print(text.split(" "))
5 8 ['Python', 'is', 'a', '', 'great', '', '', 'language']
The sentence has 5 words. split(" ") reports 8 because of the 3 empty strings.
Note that split() counts "don't" as one word and "well-known" as one word, because it only looks at whitespace. A hyphen or an apostrophe does not separate words.