Skip to content

Commit 86d63b2

Browse files
authored
Create count_consonants.py
1 parent c1dc8e9 commit 86d63b2

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

strings/count_consonants.py

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
def count_consonants(s: str) -> int:
2+
"""
3+
Count the number of consonants in a given string.
4+
5+
:param s: Input string to count consonants in.
6+
:return: Number of consonants in the input string.
7+
8+
Examples:
9+
>>> count_consonants("hello world")
10+
7
11+
>>> count_consonants("HELLO WORLD")
12+
7
13+
>>> count_consonants("123 hello world")
14+
7
15+
>>> count_consonants("")
16+
0
17+
>>> count_consonants("a quick brown fox")
18+
10
19+
>>> count_consonants("the quick BROWN fox")
20+
13
21+
>>> count_consonants("PYTHON")
22+
5
23+
"""
24+
if not isinstance(s, str):
25+
raise ValueError("Input must be a string")
26+
27+
consonants = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"
28+
return sum(1 for char in s if char in consonants)
29+
30+
31+
if __name__ == "__main__":
32+
from doctest import testmod
33+
34+
testmod()

0 commit comments

Comments
 (0)