String से Consonants Remove करना
इस Problem के लिए Regular Expressions का उपयोग करना सबसे आसान है। आप Multiple Characters को "|" से Separate कर सकते हैं और re.sub(chars_to_replace, string_to_replace_with, str) का उपयोग कर सकते हैं।
उदाहरण: Explicit Consonant List के साथ
>>> import re
>>> consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z']
>>> re.sub('|'.join(consonants), "", "Hello people", flags=re.IGNORECASE)
"eo eoe"
Note: Regex में [] का उपयोग करके Characters का Group बनाना भी संभव है।
Simpler Version: केवल Vowels रखें
यदि आप केवल Vowels रखना चाहते हैं और बाकी सभी Characters Remove करना चाहते हैं, तो आप आसान Version उपयोग कर सकते हैं। ध्यान दें कि यह Spaces, Numbers आदि भी Remove कर देगा।
>>> import re
>>> re.sub('[^aeiou]', "", "Hello people", flags=re.IGNORECASE)
"eoeoe"
Filter Approach (No Regex):
>>> consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z'] >>> s = "Hello people" >>> ''.join(c for c in s if c.lower() not in consonants) 'eo eoe'
Performance Comparison:
- Regex [^aeiou]: Fastest for Simple Cases
- Filter + Generator: Readable, No Regex Overhead
- Explicit Consonant List: Most Control, लेकिन Verbose