Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

ตรวจสอบ Vowel/Consonant ใน Python

เช็คตัวอักษรเป็น Vowel (สระ) หรือ Consonant (พยัญชนะ)

ฟังก์ชันตรวจสอบ

def vowel_or_consonant(c):
    if not c.isalpha():
        return 'Neither'
    vowels = 'aeiou'
    if c.lower() in vowels:
        return 'Vowel'
    else:
        return 'Consonant'

for c in "hello people":
    print(c, vowel_or_consonant(c))

Output

h Consonant
e Vowel
l Consonant
l Consonant
o Vowel
  Neither
p Consonant
e Vowel
o Vowel
p Consonant
l Consonant
e Vowel

ขยาย: รองรับ Unicode (Thai, Accented)

import unicodedata

def is_vowel(c):
    if not c.isalpha():
        return False
    # Normalize และเช็ค Base Character
    base = unicodedata.normalize('NFD', c)[0].lower()
    return base in 'aeiou'