Only the Last One

Python for AIHard+10 XP+10

Only the Last One

.replace(old, new, 1) swaps the first match. A file-renaming tool needs to swap only the last one, for example to change the final - in a date.

Task: write replace_last(text, old, new) that returns text with only the last match of old replaced by new.

  • If old doesn't appear, return text unchanged.
  • old is never empty.
  • "Last" means the match that starts furthest to the right. In "aaa", the last "aa" starts at position 1.

Examples

text = "one, two, one"
old = "one"
new = "three"
returns 'one, two, three'
text = "a.b.c"
old = "."
new = "-"
returns 'a.b-c'

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run