Open In App

Python | Count and display vowels in a string

Last Updated : 02 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this program, we need to count the number of vowels present in a string and display those vowels. This can be done using various methods. In this article, we will go through few of the popular methods to do this in an efficient manner. 
Examples: 

In a simple way
Input : Geeks for Geeks
Output :
5
['e', 'e', 'o', 'e', 'e']

This is in a different way
Input : Geeks for Geeks
Output : {'u': 0, 'o': 1, 'e': 4, 'a': 0, 'i': 0}

Counting vowels: String Way

In this method, we will store all the vowels in a string and then pick every character from the enquired string and check whether it is in the vowel string or not. The vowel string consists of all the vowels with both cases since we are not ignoring the cases here. If the vowel is encountered then count gets incremented and stored in a list and finally printed. 

Python3




# Python code to count and display number of vowels
# Simply using for and comparing it with a
# string containing all vowels
def Check_Vow(string, vowels):
    final = [each for each in string if each in vowels]
    print(len(final))
    print(final)
     
# Driver Code
string = "Geeks for Geeks"
vowels = "AaEeIiOoUu"
Check_Vow(string, vowels);


Output

5
['e', 'e', 'o', 'e', 'e']

Time complexity: O(n)
Auxiliary Space: O(n)

Counting vowels: Dictionary Way

This also performs the same task but in a different way. In this method, we form a dictionary with the vowels and increment them when a vowel is encountered. In this method, we use the case fold method to ignore the cases, following which we form a dictionary of vowels with the key as a vowel. This is a better and efficient way to check and find the number of each vowel present in a string. 

Python3




# Count vowels in a different way
# Using dictionary
def Check_Vow(string, vowels):
     
    # casefold has been used to ignore cases
    string = string.casefold()
     
    # Forms a dictionary with key as a vowel
    # and the value as 0
    count = {}.fromkeys(vowels, 0)
     
    # To count the vowels
    for character in string:
        if character in count:
            count[character] += 1   
    return count
     
# Driver Code
vowels = 'aeiou'
string = "Geeks for Geeks"
print (Check_Vow(string, vowels))


Output

{'a': 0, 'e': 4, 'i': 0, 'o': 1, 'u': 0}

Time complexity: O(n)
Auxiliary Space: O(n)

Counting vowels: regex way 

We can also use this method to perform this task. We can use the regular expression to perform this task. We use re.findall() method to find all the vowels in string make list with them. We use len on list to find total vowels in string. 

Python3




import re
# Count vowels in a different way
# Using re.findall
def Check_Vow(string, vowels):
     
    # Using re.findall in string
    str_list = re.findall(f'[{vowels}]', string, re.I)
     
    # printing length of string
    print(len(str_list))
     
    # Returning the list of matched element
    return str_list
     
# Driver Code
vowels = 'aeiou'
string = "Geeks for Geeks"
print (Check_Vow(string, vowels))


Output

5
['e', 'e', 'o', 'e', 'e']

Time complexity: O(n), where n is the length of the input string. The time complexity of re.findall() method is O(n) because it scans the entire string once.
Auxiliary space: O(m), where m is the number of vowels in the input string. The space complexity is proportional to the number of vowels in the input string because we are storing all the matched vowels in a list.

Another approach that could be used to count and display the vowels in a string is to use a combination of the Counter class from the collections module and the filter function.

Here is an example of how you could use this approach to solve the problem:

Python3




from collections import Counter
 
def count_and_display_vowels(string):
    vowels = 'aeiouAEIOU'
    vowels_list = filter(lambda c: c in vowels, string)
    count = Counter(vowels_list)
    return count
 
string = "Geeks for Geeks"
print(count_and_display_vowels(string))


Output

Counter({'e': 4, 'o': 1})

This code uses the filter function to create a filter object that contains only the vowels in the input string. It then uses the Counter class to count the number of occurrences of each vowel in the filter object. The Counter class is a subclass of dict that is specifically designed for counting the occurrences of elements in a list. It returns a dictionary with the elements as keys and the number of occurrences as values.

Counting vowels: recursive function way

Here we use recursive function to get the length of vowels, vowels in a given string. we recursively call the function until we reach the base condition.

Python3




#defining recursive function
def Check_Vow(start,string,newlist):
    if start==len(string):   #base condition
        return len(newlist),newlist
    if string[start] in ['a','e','i','o','u']:   #check whether element is vowel or not
        newlist.append(string[start])
    return Check_Vow(start+1,string,newlist)  #recursive calling
#driver code
string = "Geeks for Geeks"
#calling recursive function
res=Check_Vow(0,string,[])
#printing result
print(*res,sep='\n')


Output

5
['e', 'e', 'o', 'e', 'e']

Time complexity: O(n)
Auxiliary Space: O(n)

Counting vowels: Using operator.countOf() method

Python3




# Python code to count and display number of vowels
# Simply using for and comparing it with a
# string containing all vowels and operator.countOf() method
import operator as op
 
 
def Check_Vow(string, vowels):
    final = [each for each in string if op.countOf(vowels, each) > 0]
    print(len(final))
    print(final)
 
 
# Driver Code
string = "Geeks for Geeks"
vowels = "AaEeIiOoUu"
Check_Vow(string, vowels)


Output

5
['e', 'e', 'o', 'e', 'e']

Time Complexity: O(n)
Auxiliary Space: O(n)

Counting vowels: Using reduce() and lambda function: 

Algorithm:

  • Define a function named ‘check_vow’ which takes two arguments, a string and a string containing all vowels.
  • Using the reduce function, create a list of vowels in the given string.
  • Print the length of the list of vowels and the list of vowels.
  • Call the function with the given string and vowel string.

Python3




from functools import reduce
 
def check_vow(string, vowels):
    vowel_list = reduce(lambda x, y: x + [y] if y in vowels else x, string, [])
    print(len(vowel_list))
    print(vowel_list)
 
string = "Geeks for Geeks"
vowels = "AaEeIiOoUu"
check_vow(string, vowels)
#This code is contributed by Jyothi pinjala


Output

5
['e', 'e', 'o', 'e', 'e']

Time Complexity: O(n), where n is the length of the given string. The reduce function iterates over each character in the string, so the time complexity is linear with respect to the length of the string.

Auxiliary Space: O(m), where m is the number of vowels in the given string. The reduce function creates a list of vowels in the string, which is stored in memory. The space complexity is linear with respect to the number of vowels in the string.



Similar Reads

Python program to count number of vowels using sets in given string
Given a string, count the number of vowels present in the given string using Sets. You can use sets to count the number of vowels in a given string in Python. Sets are useful to efficiently check for counting the unique occurrences of vowels. Input : GeeksforGeeksOutput : No. of vowels : 5Explaination: The string GeeksforGeeks contains 5 vowels in
4 min read
Python Program to Count the Number of Vowels in a String
In this article, we will be focusing on how to print each word of a sentence along with the number of vowels in each word using Python. Vowels in the English language are: 'a', 'e', 'i', 'o', 'u'. So our task is to calculate how many vowels are present in each word of a sentence. So let us first design a simple approach that we will be following in
10 min read
Recursively Count Vowels From a String in Python
Python is a versatile and powerful programming language that provides various methods to manipulate strings. Counting the number of vowels in a string is a common task in text processing. In this article, we will explore how to count vowels from a string in Python using a recursive method. Recursion is a programming concept where a function calls i
3 min read
Python Program to Count Vowels in a String Using Recursion
Given a string, our task is to count the number of vowels in the string using recursion in Python and return the number of vowels. Examples: Input: acbedOutput: 2Input: geeksforgeeksOutput: 5Explanation: We are counting vowels in a string and printing the number of vowels.Python Program to Count Vowels in a String Using RecursionWe can use a recurs
3 min read
Python | Alternate vowels and consonants in String
Sometimes, while working with Strings in Python, we can have a problem in which we may need restructure a string, adding alternate vowels and consonants in it. This is a popular school-level problem and having solution to this can be useful. Let's discuss certain ways in which this problem can be solved. Method #1 : Using loop + join() + zip_longes
7 min read
Python Program to Count characters surrounding vowels
Given a String, the task is to write a Python program to count those characters which have vowels as their neighbors. Examples: Input : test_str = 'geeksforgeeksforgeeks' Output : 10 Explanation : g, k, f, r, g, k, f, r, g, k have surrounding vowels. Input : test_str = 'geeks' Output : 2 Explanation : g, k have surrounding vowels. Method 1 : Using
3 min read
Python Program to Count Vowels, Lines, Characters in Text File
In this article, we are going to create a python program that counts vowels, lines, and a number of characters present in a particular text file. ApproachWe have to open the file using open() function in python.Then make three variables, vowel, line and character to count the number of vowels, lines, and characters respectively.Make a list of vowel
2 min read
Python - Split String on vowels
Given a String, perform split on vowels. Example: Input : test_str = 'GFGaBst' Output : ['GFG', 'Bst'] Explanation : a is vowel and split happens on that. Input : test_str = 'GFGaBstuforigeeks' Output : ['GFG', 'Bst', 'f', 'r', 'g', 'ks']Explanation : a, e, o, u, i are vowels and split happens on that. Naive approach: Initialize variable vowels to
5 min read
Python - Replace vowels in a string with a specific character K
Given a string, replace all the vowels with character K. Input : test_str = "Geeks for Geeks"; K='#'Output : "G##ks f#r G##ks" Explanation : All the vowels in test_str are replaced by a given particular character. Input : test_list = "GFG"; K="$"Output : GFGExplanation : As test_str contained no vowel, so the same string is returned. Method #1 : Us
7 min read
Count of substrings consisting only of vowels
Given a string S, the task is to count all substrings which contain only vowels. Examples: Input: S = "geeksforgeeks" Output: 7 Explanation: Substrings {"e", "ee", "e", "o", "e", "ee", "e"} consists only of vowels. Input: S = "aecui" Output: 6 Explanation: Substrings {"a", "ae", "e", "u", "ui", "i"} consists only of vowels. Naive Approach: To simpl
11 min read