How to Find Vowels in a String in Python

Previously we printed vowels in a string in python and counted vowels in a string. Now in this post, we will find vowels in a string in python using the For Loop. The alphabets ‘A’, ‘E’, ‘I’, ‘O’, ‘U’ (in uppercase) and ‘a’, ‘e’, ‘i’, ‘o’, ‘u’ are vowels, and remaining alphabets are called consonants.

Python Program to Find Vowels in a String

We will take a string while declaring the variables. Find all vowels from the string using the For Loop, len() function, and list comprehension. Finally, the number of vowels and all vowels will be displayed on the screen.

# Python program to find vowels in a string

# take input
string = input('Enter any string: ')
# to find the vowels
vowels = [each for each in string if each in "aeiouAEIOU"]

# print number of vowels in string
print('Number of vowels in string:', len(vowels))
# print all vowels in string
print(vowels)

Output for the input values test-case-1:-

Enter any string: Know Program
Number of vowels in string: 3
[‘o’, ‘o’, ‘a’]

Output for the input values test-case-2:-

Enter any string: Learn Python Language
Number of vowels in string: 7
[‘e’, ‘a’, ‘o’, ‘a’, ‘u’, ‘a’, ‘e’]

Find Vowels in String in Python

We can also take the help of a function to find vowels in a string in python. A function is a block of code that performs a specific task.

# Python program to find vowels in a string

def findVowels(string):    #user-defined function
    # to find the vowels
    vowels = [each for each in string if each in "aeiouAEIOU"]
    print('Number of vowels in string:', len(vowels))
    print(vowels)

# take input
string = input('Enter any string: ')

# calling function
findVowels(string)

Output:-

Enter any string: Python Java Cplusplus
Number of vowels in string: 5
[‘o’, ‘a’, ‘a’, ‘u’, ‘u’]

Program to Find Vowels in a String in Python

In this program, we use the casefold() method to ignore the cases. The casefold() method returns a string where all the characters are lower case. Also, we use the .fromkeys() method. The fromkeys() method creates a new dictionary from the given sequence of … ‘i’, ‘o’, ‘u’ } value = [1].

# Python program to find vowels in a string

def findVowels(string, vowels):
    
    # using dictionary
    count = {}.fromkeys(vowels, 0)
    string = string.casefold()
    
    # to find the vowels
    for char in string:
        if char in count:
           count[char] += 1
    return count

# take input
string = input('Enter any string: ')

# calling function
vowels = 'aeiou'
print(findVowels(string, vowels))

Output for the input values test-case-1:-

Enter any string: Know Program
{‘a’: 1, ‘e’: 0, ‘i’: 0, ‘o’: 2, ‘u’: 0}

Output for the input values test-case-2:-

Enter any string: Learn from Knowprogram
{‘a’: 2, ‘e’: 1, ‘i’: 0, ‘o’: 3, ‘u’: 0}

Leave a Comment

Your email address will not be published. Required fields are marked *