Python Tutorials

Python Programs

Python Count the Number of Each Vowel


Python Count the Number of Each Vowel

In this tutorial, we will learn how to count the number of each vowel in a string in Python. We will cover the basic concept of string manipulation and implement a function to perform the counting.


What is String Manipulation

String manipulation involves altering, parsing, and analyzing strings in various ways. Counting the number of each vowel in a string is a common task in text processing.


Syntax

The syntax to count the number of each vowel in a string in Python is:

def count_vowels(s):
    vowels = 'aeiou'
    s = s.lower()
    count = {vowel: s.count(vowel) for vowel in vowels}
    return count


Counting the number of each vowel in a string

We can create a function to count the number of each vowel in a given string by iterating through the vowels and counting their occurrences in the string.

For example,

  1. Define a function named count_vowels that takes one parameter s.
  2. Convert the string to lowercase to ensure case-insensitive counting.
  3. Initialize a dictionary to store the count of each vowel.
  4. Use a dictionary comprehension to iterate through each vowel and count its occurrences in the string.
  5. Return the dictionary with the counts of each vowel.
  6. Call the function with a sample string and print the result.

Python Program

def count_vowels(s):
    vowels = 'aeiou'
    s = s.lower()
    count = {vowel: s.count(vowel) for vowel in vowels}
    return count

# Sample string
sample_string = "Hello, world! Welcome to Python programming."

# Count the number of each vowel in the sample string
result = count_vowels(sample_string)

# Print the result
print('Vowel counts:', result)

Output

Vowel counts: {'a': 1, 'e': 3, 'i': 1, 'o': 6, 'u': 0}