Python Program to Calculate the Number of Words and the Number of Characters Present in a String

PythonServer Side ProgrammingProgramming

When it is required to calculate the number of words and characters present in a string,

Below is the demonstration of the same

Example

 Live Demo

my_string = "Hi there, how are you Will ? "
print("The string is :")
print(my_string)
my_chars=0
my_words=1
for i in my_string:
   my_chars=my_chars+1
   if(i==' '):
      my_words=my_words+1
print("The number of words in the string are :")
print(my_words)
print("The number of characters in the string are :")
print(my_chars)

Output

The string is :
Hi there, how are you Will ?
The number of words in the string are :
8
The number of characters in the string are :
29

Explanation

  • A string is defined, and is displayed on the console.

  • The number of characters is assigned to 0.

  • The number of words is assigned to 1.

  • The string is iterated over, and the character variable is incremented.

  • If a space is encountered, then the word count is also incremented.

  • These values are displayed on the console.

raja
Published on 16-Apr-2021 12:24:26
Advertisements