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

ลบ Consonant ออกจาก String ใน Python (Regex/Filter)

ลบพยัญชนะ (Consonants) เหลือสระ/อักขระอื่น

1. Regex: re.sub()

>>> import re
>>> consonants = 'bcdfghjklmnpqrstvwxyz'
>>> re.sub(f'[{consonants}]', '', "Hello people", flags=re.IGNORECASE)
'eo eoe'

2. Regex Inverted: เก็บแค่ Vowel

>>> re.sub(r'[^aeiou]', '', "Hello people", flags=re.IGNORECASE)
'eoeoe'  # Space/Non-alpha หายไปด้วย

3. Filter + Generator (No Regex)

>>> consonants = set('bcdfghjklmnpqrstvwxyz')
>>> s = "Hello people"
>>> ''.join(c for c in s if c.lower() not in consonants)
'eo eoe'

Performance Note

  • Filter + Set Lookup: เร็วที่สุดสำหรับ String ใหญ่
  • Regex: อ่านง่าย Flexible แต่ Overhead สูงกว่า