如何替换字符串中表达式的最后一个匹配项?

在 Python 中有没有一种快速的方法来替换字符串,而不是像 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>'
128397 次浏览

我不会假装这是最有效的方法,但这是一个简单的方法。它反转所有有问题的字符串,使用 str.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>'
>>> 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'

下面是这个问题的递归解决方案:

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

如果你知道‘ old’字符串不包含任何特殊字符,你可以使用 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>'

只要反转字符串,替换第一个匹配项,然后再次反转它:

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)

产出:

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.

这是 一句话:

result = new.join(s.rsplit(old, maxreplace))

返回字符串 是的的一个副本,其中子字符串 老了的所有匹配项都替换为 新的。替换第一个 Maxplace出现。

以及正在使用的完整 例子:

s = 'mississipi'
old = 'iss'
new = 'XXX'
maxreplace = 1


result = new.join(s.rsplit(old, maxreplace))
>>> result
'missXXXipi'

试试这个:

def replace_last(string, old, new):
old_idx = string.rfind(old)
return string[:old_idx] + new + string[old_idx+len(old):]

类似地,您可以通过用 Find () 替换 < strong > string.rfind () 来替换第一个匹配项。

希望能有所帮助。

如果你有一个字符串列表,你可以在一行中使用列表内涵和字符串切片来覆盖整个列表。.不需要使用函数;

myList = [x[::-1].replace('<div>'[::-1],'<bad>'[::-1],1)[::-1] if x.endswith('<div>') else x for x in myList]

我使用 如果 别的来保持列表中不符合替换条件的项目,否则您的列表将只是符合条件的项目。