Python Program to Count Words in a String

Counting words in a string is a common task in text processing and data analysis. It helps in understanding string manipulation and built-in Python methods.

In this tutorial, we will explore multiple approaches to count words in Python.

1. Understanding the Problem

Given a string, count the number of words present.

Input: Hello world from Python
Output: 4

2. Method 1: Using split()

Python
string = input("Enter a sentence: ")
words = string.split()

print("Number of words:", len(words))

The split() method separates the string into words based on spaces.

3. Method 2: Using For Loop

Python
string = input()
count = 0

for word in string.split():
    count += 1

print(count)

This method manually counts each word.

4. Method 3: Using Function

Python
def count_words(s):
    return len(s.split())

print(count_words("Python is easy to learn"))

Functions make the code reusable and cleaner.

5. Method 4: Using Regular Expressions

Python
import re

string = input()
words = re.findall(r'\b\w+\b', string)

print(len(words))

Regex helps handle complex cases like punctuation.

6. Method 5: Counting Spaces

Python
string = input()

if string.strip() == "":
    print(0)
else:
    count = string.count(" ") + 1
    print(count)

This method assumes words are separated by single spaces.

7. Algorithm

1. Take input string.

2. Split string into words.

3. Count number of elements.

4. Print result.

8. Common Mistakes

1. Not handling multiple spaces.

2. Ignoring empty strings.

3. Miscounting due to punctuation.

4. Assuming fixed spacing.

9. Applications

1. Text analysis.

2. NLP preprocessing.

3. Document statistics.

4. Chat applications.

Conclusion

Counting words is an essential string operation in Python used in many real-world applications.

Different methods provide flexibility based on complexity and performance needs.