Write a Python function to count the number of vowels in a string.
Posted by MaryJns
Last Updated: August 20, 2024
Counting Vowels in a String using Python
Vowels play a crucial role in language, and counting them in a string can be useful for various applications such as text analysis or natural language processing. Below is a Python function that efficiently counts the number of vowels in a given string.
def count_vowels(input_string):
    # Define a set of vowels for easy lookup
    vowels = set("aeiouAEIOU")
    
    # Initialize a counter to keep track of vowel count
    vowel_count = 0
    
    # Iterate over each character in the input string
    for char in input_string:
        if char in vowels:
            vowel_count += 1
    
    return vowel_count

# Example usage
example_string = "Hello, World!"
print(f"The number of vowels in the string '{example_string}' is: {count_vowels(example_string)}")
Explanation:
1. Function Definition: - The function count_vowels takes a single argument input_string, which is the string in which vowels will be counted. 2. Vowel Set: - A set named vowels is created containing both lowercase and uppercase vowel characters. Using a set allows for O(1) average time complexity for membership checks. 3. Counter Initialization: - A variable vowel_count is initialized to zero. This variable will accumulate the total number of vowels found. 4. Character Iteration: - The function iterates through each character in the input string. If a character is found in the vowels set, the counter is incremented. 5. Return Value: - Finally, the function returns the total count of vowels found in the input string.
Example Use Case:
In the provided example, the function is tested with the string "Hello, World!", and the output will indicate the total number of vowels present in that string, demonstrating its practical application. This function is efficient and can handle strings of any length, making it a versatile tool for text analysis.