rreplace - How to replace the last occurrence of an expression in a string?
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Luau
--
Chapters
00:00 Question
00:30 Accepted answer (Score 253)
00:44 Answer 2 (Score 76)
01:17 Answer 3 (Score 23)
01:46 Answer 4 (Score 16)
02:18 Thank you
--
Full question
https://stackoverflow.com/questions/2556...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #string
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Luau
--
Chapters
00:00 Question
00:30 Accepted answer (Score 253)
00:44 Answer 2 (Score 76)
01:17 Answer 3 (Score 23)
01:46 Answer 4 (Score 16)
02:18 Thank you
--
Full question
https://stackoverflow.com/questions/2556...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #string
#avk47
ACCEPTED ANSWER
Score 265
>>> def rreplace(s, old, new, occurrence):
... li = s.rsplit(old, occurrence)
... return new.join(li)
...
>>> s
'1232425'
>>> rreplace(s, '2', ' ', 2)
'123 4 5'
>>> rreplace(s, '2', ' ', 3)
'1 3 4 5'
>>> rreplace(s, '2', ' ', 4)
'1 3 4 5'
>>> rreplace(s, '2', ' ', 0)
'1232425'
ANSWER 2
Score 26
I'm not going to pretend that this is the most efficient way of doing it, but it's a simple way. It reverses all the strings in question, performs an ordinary replacement using str.replace on the reversed strings, then reverses the result back the right way round:
>>> def rreplace(s, old, new, count):
... return (s[::-1].replace(old[::-1], new[::-1], count))[::-1]
...
>>> rreplace('<div><div>Hello</div></div>', '</div>', '</bad>', 1)
'<div><div>Hello</div></bad>'
ANSWER 3
Score 18
Just reverse the string, replace first occurrence and reverse it again:
mystr = "Remove last occurrence of a BAD word. This is a last BAD word."
removal = "BAD"
reverse_removal = removal[::-1]
replacement = "GOOD"
reverse_replacement = replacement[::-1]
newstr = mystr[::-1].replace(reverse_removal, reverse_replacement, 1)[::-1]
print ("mystr:", mystr)
print ("newstr:", newstr)
Output:
mystr: Remove last occurence of a BAD word. This is a last BAD word.
newstr: Remove last occurence of a BAD word. This is a last GOOD word.
ANSWER 4
Score 5
If you know that the 'old' string does not contain any special characters you can do it with a regex:
In [44]: s = '<div><div>Hello</div></div>'
In [45]: import re
In [46]: re.sub(r'(.*)</div>', r'\1</bad>', s)
Out[46]: '<div><div>Hello</div></bad>'