Python Program to Count Words in String
You can count words in a string in Python by using
len(string.split()), which splits the string by spaces and counts the resulting parts.Examples
InputHello world
Output2
InputPython programming is fun
Output4
Input
Output0
How to Think About It
To count words in a string, think of words as groups of characters separated by spaces. Splitting the string by spaces creates a list of words, and counting the list's length gives the number of words.
Algorithm
1
Get the input string2
Split the string into parts using spaces as separators3
Count how many parts are in the list4
Return or print the countCode
python
text = input("Enter a string: ") words = text.split() count = len(words) print("Number of words:", count)
Output
Enter a string: Hello world
Number of words: 2
Dry Run
Let's trace the input 'Hello world' through the code
1
Input string
text = 'Hello world'
2
Split string
words = ['Hello', 'world']
3
Count words
count = 2
4
Print result
Output: Number of words: 2
| Step | Words List | Count |
|---|---|---|
| Split string | ['Hello', 'world'] | 2 |
Why This Works
Step 1: Splitting the string
The split() method breaks the string into a list of words separated by spaces.
Step 2: Counting words
Using len() on the list gives the total number of words.
Step 3: Printing the result
The program prints the count so the user can see how many words were in the input.
Alternative Approaches
Using a loop to count words
python
text = input("Enter a string: ") count = 0 for word in text.split(): count += 1 print("Number of words:", count)
This method manually counts words by looping, which is more verbose but shows the counting process clearly.
Using regular expressions
python
import re text = input("Enter a string: ") words = re.findall(r'\b\w+\b', text) print("Number of words:", len(words))
This method counts words more precisely by matching word patterns, useful if input has punctuation.
Complexity: O(n) time, O(n) space
Time Complexity
Splitting the string scans each character once, so time grows linearly with input size.
Space Complexity
The split method creates a list of words, so extra space grows with the number of words.
Which Approach is Fastest?
Using split() and len() is fastest and simplest for most cases; regex is slower but more precise.
| Approach | Time | Space | Best For |
|---|---|---|---|
| split() and len() | O(n) | O(n) | Simple word counts |
| Loop counting | O(n) | O(n) | Learning counting process |
| Regex findall | O(n) | O(n) | Handling punctuation accurately |
Use
split() to easily separate words by spaces before counting.Beginners often forget to handle empty strings, which can cause incorrect counts.