Python Program to find the number of words and characters in a string

How to Count words and characters in a python string?

In this string python program, we need to calculate the number of characters and words in a string. Let us check an example " I love my country" In this string, we have the word count as 4 and character count 17. 

To solve this python problem, Initialize two variables: counting the words and counting the characters. The word counter is incremented every time space is found in the string. And the character count is incremented until the last character is found. 

Hereafter accepting the user's input and saving that input to a variable, initialize two variables as we told for words and characters. Then we open a for loop until the string's length, and we increment the character count every time the loop iterates, and the word count is incremented when we encounter space in the string. Finally, print the word count and character count. 


STEP 1: Accept the string from the user and save that to a variable using the input method in python.

STEP 2: Initialize two variables for word count and character count.

STEP 3: Open a for loop till the length of the string to take each character of the string,

STEP 4: Increment the character count in every loop iteration.

STEP 5: Check using the if condition that the character is a blank space. if so increment the word counter.

STEP 6: Print the word counter and character count separately using print statement in a python programming language.

Python Source Code

                                          string=input("Enter string:")
for i in string:
      if(i==' '):
print("Number of words :")
print("Number of characters :")


Enter the string : I Love My Country

Number of words : 4

Number of characters : 17