20

Phase 5 - Category 2: Counting & Analysis

Chapter 20 • Intermediate

75 min

Phase 5 - Category 2: Counting & Analysis

Introduction

Learn to analyze strings by counting different types of characters, finding frequencies, and extracting statistical information.

Key Concepts

Character Counting

  • Vowels & Consonants: Count letters by type
  • Digits, Letters, Special: Categorize characters
  • Uppercase/Lowercase: Count by case
  • Frequency Analysis: Count occurrences of each character

Character Classification

  • Vowels: a, e, i, o, u (and uppercase)
  • Consonants: All other letters
  • Digits: 0-9
  • Special Characters: Everything else

String Methods

  • char.isalpha(): Check if letter
  • char.isdigit(): Check if digit
  • char.isupper(): Check if uppercase
  • char.islower(): Check if lowercase
  • char.isspace(): Check if space

Common Patterns

Count Vowels

python.js
vowels = "aeiouAEIOU"
count = 0
for char in text:
    if char in vowels:
        count += 1

Frequency Dictionary

python.js
freq = {}
for char in text:
    freq[char] = freq.get(char, 0) + 1

Problem-Solving Approach

  1. Iterate: Loop through each character
  2. Classify: Determine character type
  3. Count: Increment appropriate counter
  4. Store: Use dictionary for frequency analysis

Hands-on Examples

Count Vowels and Consonants

# Take string input
text = input("Enter a string: ")

# Count vowels and consonants
vowels = "aeiouAEIOU"
vowel_count = 0
consonant_count = 0

for char in text:
    if char.isalpha():  # Only count letters
        if char in vowels:
            vowel_count += 1
        else:
            consonant_count += 1

print(f"Vowels: {vowel_count}")
print(f"Consonants: {consonant_count}")

Iterate through string, check if character is letter. If vowel, increment vowel count; otherwise increment consonant count.