Python program to Count words, characters and space of a string
Python program to count words, characters and space of a string
In this article, we will discuss the concept of the Python program to Count words, character and Space in a string
In this post, we are going to learn how to count words, character and space of the given String in Python programming language
Count words, character and Space using for loop
The program allows the user to enter a String and then it counts and display the total number of words, character and Space of the given string using for loop in Python programing language
Program 1
str=raw_input("Enter String") #Python 2,7 char=0 word=1 for i in str: char=char+1 if(i==' '): word=word+1 print("Number of words in the given string ",word) print("Number of characters in the given string ",char) print("Number of space in the given string ",(word-1))
When the above code is executed, it produces the following result
Enter String: Python programming language Number of words in the given string 3 Number of characters in the given string 27 Number of space in the given string 2
Approach
- Declare a String variable as str;
- Declare and initialize integer variables as int words=1, characters=0;
- The user asked to enter a string
- The given string is stored in the variable str;
- A for-loop is used to count every total of the given string.
- variable char incremented by 1 inside the for loop
- Use an if condition to test if(i==’ ‘): If it is true, The words becomes words + 1(wordss=words+1);
- Finally, the program displays the total number of the words, character and Space of the given string
Program 2
The program allows the user to enter a String and then it counts and display the total number of words, character and Space of the given string using the built-in function in Python programing language
wordCount=0#Python 3.0 charCount=0 str=input("Enter the string\n") split_str=str.split() wordCount=len(split_str) for word in split_str: charCount+=len(word) print("Total words in the given string ",wordCount) print("Total characters in the given string ",charCount) print("Number of space in the given string ",(wordCount-1))
When the above code is executed, it produces the following result
Enter the string Basic Python language Total words in the given string 3 Total characters in the given string 19 Number of space in the given
Suggested for you
Similar post
C++ code to count the total number of characters in the given string
C code to count the total number of characters in the given string
Python code to count the total number of characters in the given string
Java program to count the total number of characters in the given string including space
C program to count the total number of characters in the given string including space
C++ program to count the total number of characters in the given string including space