Python | Counting and displaying vowels in a string

Counters | Python Methods and Functions | String Variables

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} 

Vowel Counting: String Path

In this method, we will store all vowels in a string and then select each character from the requested string and check if it is in the vowel string or not. The vowel string consists of all vowels in both cases, as we are not ignoring those cases here. If a vowel is encountered, the counter is incremented and stored in the list and finally printed.

# Python code for counting and displaying the number of vowels
# Just using for and comparing it with
# the string that connects 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 = "AeEeIiOoUu"

Check_Vow (string, vowels); 

Output:

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

Vowel counting: dictionary path

This is also performs the same task, but in a different way. In this method, we build a vocabulary with vowels and increment them when vowels are detected. In this method, we use the case fold method to ignore the cases, after which we build a vowel dictionary with the key as the vowel. This is the best and most efficient way to check and find the number of each vowel in a line.

# Read vowels differently
# Using the dictionary

def Check_Vow (string, vowels):

 

# casefold was used to ignore cases

string = string.casefold ()

 

# Forms a dictionary with a key as a vowel

# and value as 0

  count = {}. fromkeys (vowels, 0 )

 

# To count vowels

for character in string:

if character in count:

count [character] + = 1  

return co unt

 
Driver code

vowels = 'aeiou'

string = "Geeks for Geeks"

print (Check_Vow (string, vowels))

Output:

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




Tutorials