English

Write a program to input line(s) of text from the user until enter is pressed. Count the total number of characters in the text (including white spaces), the total number of alphabets

Advertisements
Advertisements

Question

Write a program to input line(s) of text from the user until enter is pressed. Count the total number of characters in the text (including white spaces), the total number of alphabets, the total number of digits, the total number of special symbols, and the total number of words in the given text. (Assume that each word is separated by one space).

Answer in Brief
Advertisements

Solution

Program:
userInput = input("Write a sentence: ")
#Count the total number of characters in the text (including white spaces)which is the length of string
totalChar = len(userInput)
print("Total Characters: ",totalChar)
#Count the total number of alphabets,digit and special characters by looping through each character and incrementing the respective variable value
totalAlpha = totalDigit = totalSpecial = 0
for a in userInput:
    if a.isalpha():
        totalAlpha += 1
    elif a.isdigit():
        totalDigit += 1
    else:
        totalSpecial += 1

print("Total Alphabets: ",totalAlpha)
print("Total Digits: ",totalDigit)
print("Total Special Characters: ",totalSpecial)

#Count number of words (Assume that each word is separated by one space)
#Therefore, 1 space:2 words, 2 space:3 words and so on
totalSpace = 0
for b in userInput:
    if b.isspace():
        totalSpace += 1

print("Total Words in the Input :",(totalSpace + 1))

OUTPUT:
Write a sentence: Good Morning!
Total Characters: 13
Total Alphabets: 11
Total Digits: 0
Total Special Characters: 2
Total Words in the Input: 2 
shaalaa.com
String Handling in Python
  Is there an error in this question or solution?
Chapter 8: Strings - Exercise [Page 188]

APPEARS IN

NCERT Computer Science [English] Class 11
Chapter 8 Strings
Exercise | Q 1. | Page 188
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×