Check if a letter is a Vowel in Python

avatar

Borislav Hadzhiev

Last updated: Sep 20, 2022

banner

Photo from Unsplash

Check if a letter is a Vowel in Python #

Use the in operator to check if a letter is a vowel, e.g. if my_str[0] in vowels:. The in operator will return True if the letter is a vowel and False otherwise.

main.py
vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'] my_str = 'bobbyhadz' if my_str[0] in vowels: print('The letter is a vowel') else: # 👇️ this runs print('The letter is a consonant') my_str = 'abcde' print(my_str[0] in vowels) # 👉️ True print(my_str[1] in vowels) # 👉️ False print(my_str[-1] in vowels) # 👉️ True

The vowels variable stores a list containing the lowercase and uppercase vowels.

The in operator tests for membership. For example, x in l evaluates to True if x is a member of l, otherwise it evaluates to False.

The following example checks if the first letter of the string is a vowel.

main.py
vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'] my_str = 'bobbyhadz' if my_str[0] in vowels: print('The letter is a vowel') else: # 👇️ this runs print('The letter is a consonant')

If the letter is not a vowel, then it is a consonant.

Python indexes are zero-based, so the first character in a string has an index of 0, and the last character has an index of -1 or len(my_str) - 1.
main.py
vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'] my_str = 'abcde' print(my_str[0] in vowels) # 👉️ True print(my_str[1] in vowels) # 👉️ False print(my_str[-1] in vowels) # 👉️ True

Negative indices can be used to count backward, e.g. my_str[-1] returns the last character in the string and my_str[-2] returns the second-to-last character.

You can use a for loop to check if each letter in a string is a vowel or a consonant.

main.py
vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'] my_str = 'abcde' vowels_in_string = [] for char in my_str: if char in vowels: print(f'{char} is a vowel') if char not in vowels_in_string: vowels_in_string.append(char) else: print(f'{char} is a consonant') # a is a vowel # b is a consonant # c is a consonant # d is a consonant # e is a vowel print(vowels_in_string) # 👉️ ['a', 'e']

We used the list.append() method to append the vowels from the string to a new list.

The list.append() method adds an item to the end of the list.

main.py
my_list = ['bobby', 'hadz'] my_list.append('com') print(my_list) # 👉️ ['bobby', 'hadz', 'com']

The method returns None as it mutates the original list.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.