Python中是否有一种快速替换字符串的方法,而不是从头开始,而是replace从结尾开始?例如:
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'