ByteBoard Notes Notes

Count and display the number of vowels, consonants, uppercase and lowercase characters in a string

Computer Science XI · Experiment 15 of 27 · Python

★ CBSE suggested11-CSPython programs
Expt. No.15
Page No.30

Count characters in a string

Aim

To write a Python program that counts the vowels, consonants, uppercase and lowercase characters in a string.

Concepts used

Algorithm

  1. Input a string and set four counters to 0.
  2. For each character, skip it if it is not a letter.
  3. If it is in "aeiouAEIOU", add 1 to vowels, else to consonants.
  4. If it is uppercase, add 1 to upper, else to lower.
  5. Display the four counts.

Program

# Count vowels, consonants, uppercase and lowercase characters text = input("Enter a string: ")vowels = consonants = upper = lower = 0for ch in text:    if ch.isalpha():        if ch in "aeiouAEIOU":            vowels += 1        else:            consonants += 1        if ch.isupper():            upper += 1        else:            lower += 1print("Vowels     :", vowels)print("Consonants :", consonants)print("Uppercase  :", upper)print("Lowercase  :", lower)

A marked line continues the line above it. In your file, write it on the same line.

Output

$ python count_characters_in_string.py
Enter a string: Hello World From KVS Vowels : 4 Consonants : 13 Uppercase : 6 Lowercase : 11

✓ Printed by running this program, not typed by hand.

Result

"Hello World From KVS" has 17 letters: 4 vowels and 13 consonants, of which 6 are uppercase and 11 lowercase. The three spaces were not counted.

Viva voce: what the examiner may ask

01What does isalpha() return for a space or a digit?

False. Only letters return True, so spaces and digits are skipped.

02What does ch in "aeiouAEIOU" check?

Membership: whether the character appears anywhere in that string.

03What does vowels = consonants = upper = lower = 0 do?

It is multiple assignment: all four variables get the value 0.

04Why is isupper() checked separately from the vowel test?

A letter is both a vowel or consonant and either uppercase or lowercase, so both counts are needed.

Variations for the lab test

  1. Also count digits, spaces and special characters.
  2. Count each vowel separately.
  3. Display the string with all vowels replaced by *.
! Common mistake Counting consonants without the isalpha() check adds spaces, digits and punctuation to the consonant count.
Back to the 11-CS index