Giải quyết bằng cách reverse string, reverse string cần replace, replace string với reverse của replacement, cuối cùng reverse lại kết quả.
Reverse string bằng slicing [::-1]. Replace dùng str.replace(old, new, count). Ví dụ:
def rreplace(s, old, new):
return (s[::-1].replace(old[::-1], new[::-1], 1))[::-1]
rreplace('Helloworld, hello world, hello world', 'hello', 'hi')
Output:
'Hello world,hello world, hi world'
Cách 2: reverse split string 1 lần trên old string và join list với new string. Ví dụ:
def rreplace(s, old, new):
li = s.rsplit(old, 1) # Split chỉ 1 lần
return new.join(li)
rreplace('Helloworld, hello world, hello world', 'hello', 'hi')
Output:
'Hello world, hello world, hi world'