rreplace – 如何replacestring中expression式的最后一次出现?

有没有在Python中快速的方式来取代string,而不是从开始就像replace一样从头开始? 例如:

 >>> def rreplace(old, new, occurrence) >>> ... # Code to replace the last occurrences of old by new >>> '<div><div>Hello</div></div>'.rreplace('</div>','</bad>',1) >>> '<div><div>Hello</div></bad>' 
 >>> 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' 

我不会假装这是最有效的方法,但这是一个简单的方法。 它颠倒了所有有问题的string,在反转的string上使用str.replace执行普通的replace,然后将结果反转回正确的方向:

 >>> 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>' 

如果你知道“旧”string不包含任何特殊字符,你可以用正则expression式来完成:

 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>' 

下面是该问题的recursion解决scheme:

 def rreplace(s, old, new, occurence = 1): if occurence == 0: return s left, found, right = s.rpartition(old) if found == "": return right else: return rreplace(left, old, new, occurence - 1) + new + right