Python program to Count words in a given string?

Sometimes we need to count the number of words in a given string. Python provides several approaches to accomplish this task, from manual counting using loops to built-in methods like split().

Using For Loop

This method counts words by detecting whitespace characters manually ?

test_string = "Python is a high level language. Python is interpreted language."
total = 1

for i in range(len(test_string)):
    if test_string[i] == ' ' or test_string[i] == '\n' or test_string[i] == '\t':
        total = total + 1

print("Total Number of Words:", total)
Total Number of Words: 11

Using While Loop

Similar approach using a while loop instead of for loop ?

test_string = "Python is a high level language. Python is interpreted language."
total = 1
i = 0

while i < len(test_string):
    if test_string[i] == ' ' or test_string[i] == '\n' or test_string[i] == '\t':
        total = total + 1
    i += 1

print("Total Number of Words:", total)
Total Number of Words: 11

Using a Custom Function

Creating a reusable function to count words ?

def count_words(text):
    word_count = 1
    for i in range(len(text)):
        if text[i] == ' ' or text[i] == '\n' or text[i] == '\t':
            word_count += 1
    return word_count

test_string = "Python is a high level language. Python is interpreted language."
total = count_words(test_string)
print("Total Number of Words:", total)
Total Number of Words: 11

Using Built-in split() Method

The most efficient and reliable approach using Python's built-in split() method ?

test_string = "Python is a high level language. Python is interpreted language."
words = test_string.split()
total = len(words)

print("Words:", words)
print("Total Number of Words:", total)
Words: ['Python', 'is', 'a', 'high', 'level', 'language.', 'Python', 'is', 'interpreted', 'language.']
Total Number of Words: 10

Comparison

Method Accuracy Code Length Best For
For/While Loop Good Long Learning purposes
Custom Function Good Medium Reusable code
split() method Excellent Short Production code

Conclusion

The split() method is the most reliable and efficient way to count words in a string. Manual counting with loops is useful for understanding the logic but may miss edge cases like multiple spaces.

Updated on: 2026-03-25T05:54:11+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements