
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python Program to Calculate the Number of Words and the Number of Characters Present in a String
When it is required to calculate the number of words and characters present in a string,
Below is the demonstration of the same
Example
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.
- Related Articles
- Python program to calculate the number of digits and letters in a string
- Python Program to Count Number of Lowercase Characters in a String
- Java Program to count the number of words in a String
- C# program to count the number of words in a string
- Python program to count number of substring present in string
- Count Number of Lowercase Characters in a String in Python Program
- C program to count characters, lines and number of words in a file
- PHP program to find the number of characters in the string
- Program to count number of distinct characters of every substring of a string in Python
- Reverse the words in the string that have an odd number of characters in JavaScript
- Count the Number of matching characters in a pair of string in Python
- Sorting string of words based on the number present in each word using JavaScript
- Finding the number of words in a string JavaScript
- Program to check minimum number of characters needed to make string palindrome in Python
- How to count the number of words in a string in R?

Advertisements