To count consonants in a string in Python:
vowels = "aeiouAEIOU"
my_string = "Hello World!"
count = 0
for char in my_string:
if char.isalpha() and char not in vowels:
count += 1
print(count)
The result:
7
Function to Count Consonants
Here is a function to count consonants in a string in Python:
def count_consonants(my_string: str) -> int:
"""
Function to count consonants in a given string
:param my_string: The input string
:return: The count of consonants in the input string
"""
vowels = "aeiouAEIOU"
count = 0
for char in my_string:
if char.isalpha() and char not in vowels:
count += 1
return count
example_string = "Hello World!"
print(count_consonants(example_string))
The result:
7
Add a Pytest test
To test the “count_consonants” function using Pytest:
import pytest
# Assuming that the count_consonants function is stored under app.string_operations
from app.string_operations import count_consonants
@pytest.mark.parametrize(
"input_string, expected_output",
[
("Hello World!", 7),
("Universe", 4),
("Universe!", 4),
("", 0),
(" ", 0),
("!", 0),
],
)
def test_count_consonants(input_string, expected_output):
"""
Test the count_consonants across different input strings
:param input_string: The input string to be tested
:param expected_output: The expected count of consonants in the string
:return:
"""
assert count_consonants(input_string) == expected_output
The result:
============================= test session starts =============================
collecting ... collected 6 items
test_string_operations.py::test_count_consonants[Hello World!-7] PASSED [' 16%']
test_string_operations.py::test_count_consonants[Universe-4] PASSED [' 33%']
test_string_operations.py::test_count_consonants[Universe!-4] PASSED [ '50%']
test_string_operations.py::test_count_consonants[-0] PASSED [ '66%']
test_string_operations.py::test_count_consonants[ -0] PASSED [ '83%']
test_string_operations.py::test_count_consonants[!-0] PASSED ['100%']
============================== 6 passed in '0.02s' ==============================
Additional Exercises
- Find the Max value in a Python List without using the max function
- Find the Min value in a Python List without using the min function
- Count the Number of Characters in a String in Python (without using the len function)
- How to Reverse a String in Python
- Count the Number of Spaces in a String in Python
- Count Vowels in a String in Python
- Count the number of times a character appears in a string in Python
- Find the Middle Item in a Python List