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

Count and Display Vowels ใน String Python: นับและแสดงสระในสตริง

ได้สตริง ต้องการนับและแสดงสระ (a, e, i, o, u) ที่ปรากฏ

วิธี 1: ใช้ set หา Unique Vowels


stringA = "Tutorialspoint is best"
vowels = "AaEeIiOoUu"
unique_vowels = {ch for ch in stringA if ch in vowels}
print(unique_vowels)  # {'a', 'e', 'i', 'o', 'u'}

วิธี 2: ใช้ dict.fromkeys() นับจำนวนแต่ละสระ


stringA = "Tutorialspoint is best".casefold()
vowels = "aeiou"
count = {}.fromkeys(vowels, 0)
for ch in stringA:
    if ch in count:
        count[ch] += 1
print(count)  # {'a': 1, 'e': 1, 'i': 3, 'o': 2, 'u': 1}

สรุป

  • วิธี 1: ได้ Unique Vowels (เซต)
  • วิธี 2: ได้ Count ทุกสระ (Dict) ใช้ casefold() จัดการ Unicode/Case-insensitive ดีกว่า lower()