String से Multiple Characters Remove करना
String Class में replace Method होता है जिसका उपयोग String में Substrings Replace करने के लिए किया जा सकता है। हम इस Method का उपयोग उन Characters को Empty String से Replace करने के लिए कर सकते हैं जिन्हें हम Remove करना चाहते हैं।
Single Character Remove करना:
>>> "Hello people".replace("e", "")
'Hllo popl'
Multiple Characters - Regex का उपयोग (Best):
यदि आप एक Single Line में String से Multiple Characters Remove करना चाहते हैं, तो Regular Expressions उपयोग करना बेहतर है। आप Multiple Characters को "|" से Separate कर सकते हैं और re.sub(chars_to_replace, string_to_replace_with, str) का उपयोग कर सकते हैं।
>>> import re
>>> re.sub("e|l", "", "Hello people")
'Ho pop'
Character List से Regex बनाना:
>>> import re
>>> char_list = ['a', 'e', 'i', 'o', 'u']
>>> re.sub("|".join(char_list), "", "Hello people")
'Hll ppl'
Note: Regex में [] का उपयोग करके Characters का Group बनाना भी संभव है (अधिक Efficient):
>>> re.sub("[aeiou]", "", "Hello people", flags=re.IGNORECASE)
'Hll ppl'
str.translate() का उपयोग (Fastest for Multiple Characters):
>>> # Python 3
>>> "Hello people".translate(str.maketrans('', '', 'aeiou'))
'Hll ppl'
>>> # Remove Digits
>>> "H3ll0 P30pl3".translate(str.maketrans('', '', '0123456789'))
'Hll Ppl'
Filter Approach (Readable):
chars_to_remove = set('aeiou')
result = ''.join(c for c in "Hello people" if c not in chars_to_remove)
# 'Hll ppl'
Performance Comparison:
- str.translate(): Fastest for Multiple Character Removal
- re.sub() with []: Fast, Flexible Patterns
- filter/join: Readable, No Imports Needed
- Multiple replace(): Slow for Many Characters