Word & Character Count of a Given String in Python.
Program with explanation :
# Prompting the user to input a sentence
print("Enter a sentence ")
# Getting input from the user
sentence = input()
# Splitting the sentence into words
words = sentence.split()
# Initializing counters for word count and character count
word_count = 0
character_count = 0
# Iterating through each word in the list of words
for word in words:
# Counting the number of words
word_count += 1
# Counting the number of characters in each word and adding it to the total character count
character_count += len(word)
# Printing the total number of words in the sentence
print("Total Numbers of Words in the sentence are : ", word_count)
# Printing the total number of characters in the sentence excluding spaces
print("Total Numbers of characters in the sentence excluding spaces are : ", character_count)
# Printing the total number of characters in the sentence including spaces
print("Total Numbers of characters in the sentence including spaces are : ", character_count + word_count - 1)
Explanation:
# The last print statement calculates the total number of characters in the sentence,
# including spaces, by adding the character count to the word count and then subtracting 1.
# The subtraction of 1 accounts for the spaces between words, as each space is counted
# as a character except for the space after the last word.
Here is the program :
print("Enter a sentence ")
sentence = input()
words = sentence.split()
word_count = 0
character_count = 0
for word in words:
word_count += 1
character_count += len(word)
print("Total Numbers of Words in the sentence are : ",word_count)
print("Total Numbers of characters in the sentence excluding spaces are : ",character_c
ount)
print("Total Numbers of characters in the sentence including spaces are : ",character_count+word_count-1)
Here is the output :
Enter a sentence
My name is King
Total Numbers of Words in the sentence are : 4
Total Numbers of characters in the sentence excluding spaces are : 12
Total Numbers of characters in the sentence including spaces are : 15