Python Program to Count Vowels and Consonants in String
if char.lower() in 'aeiou' and counting consonants otherwise; for example, use vowels += 1 and consonants += 1 inside the loop.Examples
How to Think About It
Algorithm
Code
string = input("Enter a string: ") vowels = 0 consonants = 0 for char in string: if char.isalpha(): if char.lower() in 'aeiou': vowels += 1 else: consonants += 1 print(f"Vowels: {vowels}, Consonants: {consonants}")
Dry Run
Let's trace the input 'hello' through the code
Initialize counters
vowels = 0, consonants = 0
Check 'h'
'h' is a letter and not a vowel, consonants = 1
Check 'e'
'e' is a vowel, vowels = 1
Check 'l'
'l' is a consonant, consonants = 2
Check second 'l'
'l' is a consonant, consonants = 3
Check 'o'
'o' is a vowel, vowels = 2
Print result
Vowels: 2, Consonants: 3
| Character | Is Letter? | Is Vowel? | Vowels Count | Consonants Count |
|---|---|---|---|---|
| h | Yes | No | 0 | 1 |
| e | Yes | Yes | 1 | 1 |
| l | Yes | No | 1 | 2 |
| l | Yes | No | 1 | 3 |
| o | Yes | Yes | 2 | 3 |
Why This Works
Step 1: Check if character is a letter
We use char.isalpha() to make sure we only count letters, ignoring numbers or symbols.
Step 2: Identify vowels
We convert the character to lowercase and check if it is in the string 'aeiou' to count vowels.
Step 3: Count consonants
If the character is a letter but not a vowel, we count it as a consonant.
Alternative Approaches
from collections import Counter string = input("Enter a string: ").lower() vowels = 'aeiou' counter = Counter(c for c in string if c.isalpha()) vowel_count = sum(counter[c] for c in vowels) consonant_count = sum(counter[c] for c in counter if c not in vowels) print(f"Vowels: {vowel_count}, Consonants: {consonant_count}")
import re string = input("Enter a string: ").lower() vowels = len(re.findall(r'[aeiou]', string)) consonants = len(re.findall(r'[bcdfghjklmnpqrstvwxyz]', string)) print(f"Vowels: {vowels}, Consonants: {consonants}")
Complexity: O(n) time, O(1) space
Time Complexity
The program loops through each character once, so the time grows linearly with the string length.
Space Complexity
Only a few counters are used, so space stays constant regardless of input size.
Which Approach is Fastest?
The simple loop method is fastest and uses least memory; alternatives like Counter or regex add overhead but can be more concise.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Simple loop | O(n) | O(1) | Beginners, fast and memory efficient |
| collections.Counter | O(n) | O(n) | Counting all letters with built-in tools |
| Regular expressions | O(n) | O(n) | Clean code if familiar with regex |