Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Phát hiện nguyên âm vs phụ âm trong Python

Trước hết kiểm tra ký tự có phải alphabet không. Sau đó tạo list nguyên âm và kiểm tra ký tự có trong list đó. Nếu không thì là phụ âm. Ví dụ:

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