Write a Python program to accept a string from the user and then print the number of vowels, consonants, digits and special characters in the string. For example, if the user enters "Hello@123", the output should be:
Vowels: 2
Consonants: 3
Digits: 3
Special characters: 1
Answer:
Answer by student
Detailed answer by teachoo
-lock-
To understand the Python program to print the number of vowels, consonants, digits and special characters in a string, we need to follow these steps:
- The program uses the input() function to accept a string s from the user.
- The program initializes four variables vowels , consonants , digits and special with the values 0 , which are the counts of vowels, consonants, digits and special characters in the string, respectively.
- The program uses a for loop to iterate over each character c of the string s .
- Inside the loop, the program checks four conditions for each character c :
- If the character is a vowel (either uppercase or lowercase), it increments the value of vowels by 1 using the += operator. The program uses the in operator to check if the character belongs to a set of characters, which are enclosed in double quotes. For example, "aeiouAEIOU" is a set of vowels.
- If the character is not a vowel and is a consonant (either uppercase or lowercase), it increments the value of consonants by 1 using the same operator. The program uses another set of characters to check for consonants, which are "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ" .
- If the character is not a vowel and not a consonant and is a digit, it increments the value of digits by 1 using the same operator. The program uses the isdigit() method to check if the character is a digit. This method returns True if the character is a digit and False otherwise.
- If none of the above conditions are true, then the character is a special character, such as punctuation marks or symbols. The program increments the value of special by 1 using the same operator.
- After looping through all the characters of the string, the program prints the values of vowels , consonants , digits and special using the print() function.
So the final code is:
-endlock-