Saturday, 29 August 2026

πŸš€ Day 65/150 – Count Consonants in a String in Python

 

πŸš€ Day 65/150 – Count Consonants in a String in Python

Consonants are all alphabet characters except vowels (a, e, i, o, u).

In Python, we can count consonants using loops, conditions, list comprehensions, and functions.

Let’s explore different methods πŸ‘‡

πŸ”Ή Method 1 – Using for Loop

text = "Python Programming" count = 0 for ch in text.lower(): if ch.isalpha() and ch not in "aeiou": count += 1 print("Consonant Count:", count)









✅ Output
Consonant Count: 13

πŸ“Œ Checks whether the character is an alphabet and not a vowel.

πŸ”Ή Method 2 – Taking User Input

text = input("Enter a string: ") count = 0 for ch in text.lower(): if ch.isalpha() and ch not in "aeiou": count += 1 print("Consonant Count:", count)









πŸ“Œ Allows users to enter any string dynamically.


πŸ”Ή Method 3 – Using List Comprehension

text = "Python Programming" count = sum([1 for ch in text.lower() if ch.isalpha() and ch not in "aeiou"]) print("Consonant Count:", count)








✅ Output
Consonant Count: 13

πŸ“Œ Cleaner and shorter Pythonic approach.

πŸ”Ή Method 4 – Using Function

def count_consonants(text): count = 0 for ch in text.lower(): if ch.isalpha() and ch not in "aeiou": count += 1 return count print(count_consonants("Python Programming"))









✅ Output

13

πŸ“Œ Best method for reusable programs.

 Key Takeaways

isalpha() ignores spaces and symbols
not in "aeiou" helps identify consonants
✅ List comprehensions make code compact
✅ Functions improve code reusability

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (119) AI (340) Android (25) AngularJS (1) Api (7) Assembly Language (2) aws (31) Azure (12) BI (10) book (1) Books (347) Bootcamp (14) C (78) C# (12) C++ (83) cloud (1) Course (90) Coursera (303) Cybersecurity (36) data (10) Data Analysis (46) Data Analytics (31) data management (16) Data Science (423) Data Strucures (18) Deep Learning (217) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (24) Finance (13) flask (4) flutter (1) FPL (17) Generative AI (77) Git (13) Google (54) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (43) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (394) Meta (24) MICHIGAN (5) microsoft (13) Nvidia (8) Pandas (16) PHP (20) Projects (34) Python (1363) Python Coding Challenge (1228) Python Library (1) Python Mathematics (14) Python Mistakes (51) Python Quiz (614) Python Tips (105) Questions (3) R (72) React (7) Scripting (3) security (4) Selenium Webdriver (4) Software (21) SQL (55) Udemy (20) UX Research (1) web application (11) Web development (9) web scraping (3)

Followers

Python Coding for Kids ( Free Demo for Everyone)