Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - String

Count vowels and consonants in a String - Python Program

Example 1 :

def count_vowels_consonants(s): vowels = "aeiouAEIOU" v_count = sum(1 for ch in s if ch.isalpha() and ch in vowels) c_count = sum(1 for ch in s if ch.isalpha() and ch not in vowels) return v_count, c_count text = "Hello World" v, c = count_vowels_consonants(text) print(f"Vowels: {v}, Consonants: {c}")

Output

 
OUTPUT  :
Vowels: 3, Consonants: 7 

Example 2 :

# Python Program to Count Vowels and Consonants in a String str1 = input("Please Enter Your Own String : ") vowels = 0 consonants = 0 str1.lower() for i in str1: if(i == 'a' or i == 'e' or i == 'i' or i == 'o' or i == 'u'): vowels = vowels + 1 else: consonants = consonants + 1 print("Total Number of Vowels in this String = ", vowels) print("Total Number of Consonants in this String = ", consonants)

Output

 
OUTPUT  :
Please Enter Your Own String : Python Programming
Total Number of Vowels in this String =  4
Total Number of Consonants in this String =  14

Example 3 :

This program uses ASCII values to find vowels and consonants.

# Python Program to Count Vowels and Consonants in a String str1 = input("Please Enter Your Own String : ") vowels = 0 consonants = 0 str1.lower() for i in str1: if(ord(i) == 65 or ord(i) == 69 or ord(i) == 73 or ord(i) == 79 or ord(i) == 85 or ord(i) == 97 or ord(i) == 101 or ord(i) == 105 or ord(i) == 111 or ord(i) == 117): vowels = vowels + 1 elif((ord(i) >= 97 and ord(i) <= 122) or (ord(i) >= 65 and ord(i) <= 90)): consonants = consonants + 1 print("Total Number of Vowels in this String = ", vowels) print("Total Number of Consonants in this String = ", consonants)

Output

 
OUTPUT  :
Please Enter Your Own String : Advanced Python Programming
Total Number of Vowels in this String =  7
Total Number of Consonants in this String =  18