How to Find Vowels in a String in Python

How to find vowels in a string in Python | We use for loop and if-else statement to find vowels in a string in python. The characters ‘A’, ‘E’, ‘I’, ‘O’, ‘U’ and ‘a’, ‘e’, ‘i’, ‘o’, ‘u’ are vowels, and the other characters are consonants.

Python Program to Find Vowels in a String

We have given the string. Find all vowels from string using for loop, list comprehension, and len() function. Finally, the number of vowels and all vowels will be printed on the screen.

# Python program to find vowels in a string

# take input
string = input('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:-

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

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

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

Find Vowels in String in Python

We will also take the 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('String: ')

# call the function
findVowels(string)

Output:-

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('String: ')

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

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

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

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

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

Leave a Comment

Your email address will not be published.