Count Consonants in String in Python

Count the number of consonants (alphabetic non-vowels) in a string.

BeginnerString ProgramsExample 4 of 25
count-consonants-in-string.py
Run in browser
1# Program to count consonants in a string
2
3s = input("Enter a string: ")
4
5vowels = "aeiouAEIOU"
6count = sum(1 for ch in s if ch.isalpha() and ch not in vowels)
7
8print("Number of consonants:", count)

Output

Enter a string: hello world
Number of consonants: 7

What's going on

We count characters that are alphabetic but not vowels.