String में Last Occurrence Replace करना
इस Problem को String को Reverse करके, Replace करने वाले String को Reverse करके, Reverse किए गए String को Replacement के Reverse से Replace करके, और अंत में Result को Reverse करके Solve किया जा सकता है।
तरीका 1: String Reversal का उपयोग
def rreplace(s, old, new):
return (s[::-1].replace(old[::-1], new[::-1], 1))[::-1]
rreplace('Hello world, hello world, hello world', 'hello', 'hi')
Output:
'Hello world, hello world, hi world'
तरीका 2: rsplit() का उपयोग (अधिक Efficient)
String को Old String पर एक बार Reverse Split करें और List को New String से Join करें।
def rreplace(s, old, new):
li = s.rsplit(old, 1) # केवल एक बार Split करें
return new.join(li)
rreplace('Hello world, hello world, hello world', 'hello', 'hi')
Output:
'Hello world, hello world, hi world'
Case-Insensitive Version:
import re
def rreplace_ignore_case(s, old, new):
# Last Occurrence Find करें (Case-insensitive)
matches = list(re.finditer(re.escape(old), s, re.IGNORECASE))
if not matches:
return s
last_match = matches[-1]
return s[:last_match.start()] + new + s[last_match.end():]
print(rreplace_ignore_case('Hello world, hello world, hello world', 'hello', 'hi'))
Performance:
rsplit/join- Fastest, Pure Pythonreversal- Slower, Creates Multiple Copiesregex- Most Flexible (Case-insensitive, Word Boundaries)