PythonMastery
Python programs · Strings · beginner

Count words in a string in Python

Count the words in a sentence with len(text.split()). Extra spaces and empty input are handled correctly, and a common mistake with split is explained.

text.split() breaks a string into a list of words. len() of that list is the number of words.

The program

python
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.

output
Enter a sentence: Python is a  great   language
Words: 5
['Python', 'is', 'a', 'great', 'language']

How it works

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:

python
text = "Python is a  great   language"

print(len(text.split()))
print(len(text.split(" ")))
print(text.split(" "))
output
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.

Learn the idea: Working with Strings, Lists & Sequences