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.
string=input("Enter string:") char=0 word=1 for i in string: char=char+1 if(i==' '): word=word+1 print("Number of words :") print(word) print("Number of characters :") print(char)
Enter the string : I Love My Country Number of words : 4 Number of characters : 17