Count and display vowels in a string in Python

PythonServer Side ProgrammingProgramming

Given a string of characters let's analyse how many of the characters are vowels.

With set

We first find out all the individual and unique characters and then test if they are present in the string representing the vowels.

Example

 Live Demo

stringA = "Tutorialspoint is best"
print("Given String: \n",stringA)
vowels = "AaEeIiOoUu"
# Get vowels
res = set([each for each in stringA if each in vowels])
print("The vlowels present in the string:\n ",res)

Output

Running the above code gives us the following result −

Given String:
Tutorialspoint is best
The vlowels present in the string:
{'e', 'i', 'a', 'o', 'u'}

with fromkeys

This function enables to extract the vowels form the string by treating it as a dictionary.

Example

stringA = "Tutorialspoint is best"
#ignore cases
stringA = stringA.casefold()
vowels = "aeiou"
def vowel_count(string, vowels):

   # Take dictionary key as a vowel
   count = {}.fromkeys(vowels, 0)

   # To count the vowels
   for v in string:
      if v in count:
   # Increasing count for each occurence
      count[v] += 1
   return count
print("Given String: \n", stringA)
print ("The count of vlowels in the string:\n ",vowel_count(stringA, vowels))

Output

Running the above code gives us the following result −

Given String:
tutorialspoint is best
The count of vlowels in the string:
{'a': 1, 'e': 1, 'i': 3, 'o': 2, 'u': 1}
raja
Published on 04-Jun-2020 11:19:26
Advertisements