Python program to Count Total Number of Words in a String

Write a Python program to Count Total Number of Words in a String with a practical example.

Python program to Count Total Number of Words in a String Example 1

This python program allows the user to enter a string (or character array). Next, it counts the total number of words present inside this string using For Loop. Here, we used Python For Loop to iterate each character in a String. Inside the For Loop, we used the If statement to check where there is a space or not. If it finds the empty space, then the total word count is incremented.

# Python program to Count Total Number of Words in a String

str1 = input("Please Enter your Own String : ")
total = 1

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

print("Total Number of Words in this String = ", total)
Python program to Count Total Number of Words in a String 1

Python program to Count Number of Words in a String Example 2

This python program for Total Number of Words in a String is the same as the above. However, we just replaced the For Loop with While Loop.

# Python program to Count Total Number of Words in a String

str1 = input("Please Enter your Own String : ")
total = 1
i = 0

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

print("Total Number of Words in this String = ", total)

Python Count Words in a String using a while loop output

Please Enter your Own String : Tutorial Gateway
Total Number of Words in this String =  2

Python program to Count Total Words in a String Example 3

This Python Count Total Number of Words in a String is the same as the first example. But, this time, we used the Functions concept to separate the Python logic.

# Python program to Count Total Number of Words in a String

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


string = input("Please Enter your Own String : ")
leng = Count_Total_Words(string)
print("Total Number of Words in this String = ", leng)

Python Count Words in a String using functions output

Please Enter your Own String : Python Hello World Program
Total Number of Words in this String =  4

About Suresh

Suresh is the founder of TutorialGateway and a freelance software developer. He specialized in Designing and Developing Windows and Web applications. The experience he gained in Programming and BI integration, and reporting tools translates into this blog. You can find him on Facebook or Twitter.