Count Consonants in String

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

PythonBeginner
Python
# Program to count consonants in a string

s = input("Enter a string: ")

vowels = "aeiouAEIOU"
count = sum(1 for ch in s if ch.isalpha() and ch not in vowels)

print("Number of consonants:", count)

Output

Enter a string: hello world
Number of consonants: 7

We count characters that are alphabetic but not vowels.