To count vowels in a string in Python:
vowels = "aeiouAEIOU"
my_string = "Hello Universe"
count = 0
for char in my_string:
if char in vowels:
count += 1
print(count)
The result:
6
Function to count the Vowels
Here is a function to count the vowels in a string in Python:
def count_vowels(my_string: str) -> int:
"""
Function to count the number of vowels in a string
:param my_string: The input string
:return: The number of vowels in the actual string
"""
vowels = "aeiouAEIOU"
count = 0
for char in my_string:
if char in vowels:
count += 1
return count
example_string = "Hello Universe"
print(count_vowels(example_string))
The result:
6
Add a Pytest test
To test the “count_vowels” function using Pytest:
import pytest
# Assuming the count_vowels function is stored under app.string_operations
from app.string_operations import count_vowels
@pytest.mark.parametrize(
"input_string, expected_output",
[("Hello Universe", 6), ("This is a new dawn", 5), ("1234", 0), ("", 0)],
)
def test_count_vowels(input_string, expected_output):
"""
Test the count_vowels function across various strings
:param input_string: The string to be tested
:param expected_output: The expected number of vowels in that string
"""
assert count_vowels(input_string) == expected_output
The result:
============================= test session starts =============================
collecting ... collected 4 items
test_string_operations.py::test_count_vowels[Hello Universe-6] PASSED [ '25%']
test_string_operations.py::test_count_vowels[This is a new dawn-5] PASSED [ '50%']
test_string_operations.py::test_count_vowels[1234-0] PASSED [ '75%']
test_string_operations.py::test_count_vowels[-0] PASSED ['100%']
============================== 4 passed in '0.01s' ==============================
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 Consonants 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