Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Program to Count characters surrounding vowels
Next article icon

Python Program to find if a character is vowel or Consonant

Last Updated : 17 Aug, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a character, check if it is vowel or consonant. Vowels are ‘a’, ‘e’, ‘i’, ‘o’ and ‘u’. All other characters (‘b’, ‘c’, ‘d’, ‘f’ ….) are consonants.

Examples:  

Input : x = 'c'
Output : Consonant

Input : x = 'u'
Output : Vowel
Recommended: Please try your approach on {IDE} first, before moving on to the solution.

We check whether the given character matches any of the 5 vowels. If yes, we print “Vowel”, else we print “Consonant”. 

Python3




# Python3 program to check if a given 
# character is vowel or consonant.
  
# Function to check whether a character 
# is vowel or not
def vowelOrConsonant(x):
  
    if (x == 'a' or x == 'e' or
        x == 'i' or x == 'o' or x == 'u'):
        print("Vowel")
    else:
        print("Consonant")
  
# Driver code
vowelOrConsonant('c')
vowelOrConsonant('e')
    
 
 
Output
Consonant  Vowel  

Time Complexity: O(1)
Auxiliary Space: O(1)

How to handle capital letters as well?  

Python3




# Python3 program to check if a given 
# character is vowel or consonant.
  
# Function to check whether a 
# character is vowel or not
def vowelOrConsonant(x):
    if (x == 'a' or x == 'e' or x == 'i' or 
        x == 'o' or x == 'u' or x == 'A' or 
        x == 'E' or x == 'I' or x == 'O' or 
        x == 'U'):
        print("Vowel")
    else:
        print("Consonant")
  
# Driver code
if __name__ == '__main__':
    vowelOrConsonant('c')
    vowelOrConsonant('E')
 
 
Output
Consonant  Vowel  

Time Complexity: O(1)
Auxiliary Space: O(1)

Python Program to find if a character is vowel or Consonant using switch case

Python3




def isVowel(ch):
    switcher = {
        'a': "Vowel",
        'e': "Vowel",
        'i': "Vowel",
        'o': "Vowel",
        'u': "Vowel",
        'A': "Vowel",
        'E': "Vowel",
        'I': "Vowel",
        'O': "Vowel",
        'U': "Vowel"
    }
    return switcher.get(ch, "Consonant")
  
# Driver Code
print('a is '+isVowel('a'))
print('x is '+isVowel('x'))
 
 
Output
a is Vowel  x is Consonant  

Time Complexity: O(1)
Auxiliary Space: O(1)

Another way is to find() the character in a string containing only Vowels.

Python3




def isVowel(ch):
  
    # Make the list of vowels
    str = "aeiouAEIOU"
    return (str.find(ch) != -1)
  
# Driver Code
print('a is '+str(isVowel('a')))
print('x is '+str(isVowel('x')))
 
 
Output
a is True  x is False  

Time Complexity: O(N)
Auxiliary Space: O(1)

Most efficient way to check Vowel using bit shift :

In ASCII these are the respective values of every vowel both in lower and upper cases.

Vowel DEC HEX BINARY

a

97 0x61 01100001

e

101 0x65 01100101

i

105 0x69 01101001

o

111 0x6F 01101111

u

117 0x75 01110101

 

A

65 0x41 01000001

E

69 0x45 01000101

I

73 0x49 01001001

O

79 0x4F 01001111

U

85 0x55 01010101

 

As very lower and upper case vowels have the same 5 LSBs. We need a number 0x208222 which gives 1 in its LSB after right-shift 1, 5, 19, 15 otherwise gives 0.  The numbers depend on character encoding.

 

DEC HEX BINARY
31 0x1F 00011111
2130466 0x208222 1000001000001000100010

 

Python3




def isVowel(ch):
  
    return (0x208222 >> (ord(ch) & 0x1f)) & 1
    # same as (2130466 >> (ord(ch) & 31)) & 1;
  
# Driver Code
print('a is '+str(isVowel('a')))
print('x is '+str(isVowel('x')))
 
 
Output
a is 1  x is 0  

Time Complexity: O(1)
Auxiliary Space: O(1)

*We can omit the ( ch & 0x1f ) part on X86 machines as the result of SHR/SAR (which is >> ) masked to 0x1f automatically.
*For machines bitmap check is faster than table check, but if the ch variable stored in register than it may perform faster.

Use regular expressions:

Using a regular expression to check if a character is a vowel or consonant. Regular expressions are a powerful tool for pattern matching and can be used to quickly and easily check if a given character matches a specific pattern.

To check if a character is a vowel using a regular expression, you can use the following code:

Python3




import re
  
def is_vowel(char):
    if re.match(r'[aeiouAEIOU]', char):
        return True
    return False
  
print(is_vowel('a'))  # Output: True
print(is_vowel('b'))  # Output: False
 
 
Output
True  False  

Time complexity: O(1), as the re.match function has a time complexity of O(1) for small strings. In this case, the string char is a single character and therefore has a small constant size.
Auxiliary space: O(1), as we are only using a constant amount of memory for the char argument and the return value.

The regular expression r'[aeiouAEIOU]’ matches any character that is a lowercase or uppercase vowel. The re.match() function searches for a match at the beginning of the string, so it will return True if the given character is a vowel and False otherwise.

This approach has the advantage of being concise and easy to understand, and it can be easily modified to check for other patterns as well. However, it may not be as efficient as some of the other approaches mentioned in the article, particularly for large inputs.

Please refer complete article on Program to find if a character is vowel or Consonant for more details!

Using ord() method:

Python3




la=[97,101,105,111,117]
ua=[65,69,73,79,85]
def isVowel(ch):
    if ord(ch) in la or ord(ch) in ua:
        return True
    return False
# Driver Code
print('a is '+str(isVowel('a')))
print('x is '+str(isVowel('x')))
 
 
Output
a is True  x is False  

Time Complexity: O(1)
Auxiliary Space: O(1)

Using operator.countOf() method

Python3




import operator as op
  
vowels="aeiouAEIOU"
  
def is_vowel(char):
    if op.countOf(vowels, char)>0:
        return True
    return False
  
print(is_vowel('a'))  # Output: True
print(is_vowel('b'))  # Output: False
 
 
Output
True  False  

Time Complexity: O(n)
Auxiliary Space: O(1)



Next Article
Python Program to Count characters surrounding vowels
author
kartik
Improve
Article Tags :
  • Python
  • Python Programs
  • vowel-consonant
Practice Tags :
  • python

Similar Reads

  • Python Program to Find ASCII Value of a Character
    Given a character, we need to find the ASCII value of that character using Python. ASCII (American Standard Code for Information Interchange) is a character encoding standard that employs numeric codes to denote text characters. Every character has its own ASCII value assigned from 0-127. Examples:
    2 min read
  • Count Vowels, Lines, Characters in Text File in Python
    We are going to create a Python program that counts the number of vowels, lines, and characters present in a given text file. Example: Assume the content of sample_text.txt is: Hello, this is a sample text file.It contains multiple lines.Counting vowels, lines, and characters.Output Total number of
    2 min read
  • Python Program to Count characters surrounding vowels
    Given a String, the task is to write a Python program to count those characters which have vowels as their neighbors. Examples: Input : test_str = 'geeksforgeeksforgeeks' Output : 10 Explanation : g, k, f, r, g, k, f, r, g, k have surrounding vowels. Input : test_str = 'geeks' Output : 2 Explanation
    3 min read
  • Python Program To Remove all control characters
    In the telecommunication and computer domain, control characters are non-printable characters which are a part of the character set. These do not represent any written symbol. They are used in signaling to cause certain effects other than adding symbols to text. Removing these control characters is
    3 min read
  • Python program to check if a word is a noun
    Given a word, the task is to write a Python program to find if the word is a noun or not using Python. Examples: Input: India Output: India is noun. Input: Writing Output: Writing is not a noun. There are various libraries that can be used to solve this problem. Approach 1: PoS tagging using NLTK C/
    1 min read
  • Python program to check if given string is vowel Palindrome
    Given a string (may contain both vowel and consonant letters), remove all consonants, then check if the resulting string is palindrome or not. Examples: Input : abcuhuvmnba Output : YES Explanation : The consonants in the string "abcuhuvmnba" are removed. Now the string becomes "auua". Input : xayzu
    5 min read
  • Python Program for Convert characters of a string to opposite case
    Given a string, convert the characters of the string into the opposite case,i.e. if a character is the lower case then convert it into upper case and vice-versa. Examples: Input : geeksForgEeksOutput : GEEKSfORGeEKSInput: hello every oneOutput: HELLO EVERY ONEExample 1: Python Program for Convert ch
    7 min read
  • Python program to equal character frequencies
    Given a String, ensure it has equal character frequencies, if not, equate by adding required characters. Input : test_str = 'geeksforgeeks' Output : geeksforgeeksggkkssfffooorrr Explanation : Maximum characters are 4 of 'e'. Other character are appended of frequency 4 - (count of chars). Input : tes
    2 min read
  • Python - Test for Word construction from character list
    Given a List and a String, test if the string can be made from list characters. Examples: Input : test_list = ['g', 'g', 'e', 'k', 's', '4', 'g', 'g', 'e', 's', 'e', 'e', '4', 'k'], test_str = 'geeks4geeks' Output : True Explanation : String can be made according to character frequencies.Input : tes
    6 min read
  • Python Program to Count the Number of Vowels in a String
    In this article, we will be focusing on how to print each word of a sentence along with the number of vowels in each word using Python. Vowels in the English language are: 'a', 'e', 'i', 'o', 'u'. So our task is to calculate how many vowels are present in each word of a sentence. So let us first des
    10 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences