rreplace-如何替换字符串中表达式的最后一次出现?


139

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

5
从对这样一个简单问题的复杂解决方案来看,这是一个很好的问题。
贾斯汀·阿迪尼

3
在下面的答案中,有一个优雅的单句需要9年(!)才能被添加到该问题中,只需向下滚动即可找到它。
John D

Answers:


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

9
非常好!在不科学的基准中替换程序中典型字符串(> 500个字符)中最后一次出现表达式时,您的解决方案比Alex的解决方案快三倍,比Mark的解决方案快四倍。感谢大家的回答!
巴泰勒米(Barthelemy)2010年

2
谢谢,它有效。该.replace方法采用第三个可选参数“ count”,该参数告诉它替换前n个出现的位置。是否会像-1那样不是很直观,但不幸的是不会这样,所以我们需要您的解决方案。
cardamom

17

我不会假装这是最有效的方法,但这是一种简单的方法。它反转所有有问题的字符串,对反转的字符串执行普通替换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>'

10

这里是单线:

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

返回字符串s的副本,其中所有出现的子字符串oldnew替换。替换第一个maxreplace事件。

以及使用中的完整示例:

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

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

1
真好!用它来删除行尾的逗号:line = "".join(line.rsplit(",", 1))同时保留后面的填充空间。
孙子

9

只需反转字符串,替换第一次出现的字符串,然后再次反转它:

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.

5

如果您知道“旧”字符串不包含任何特殊字符,则可以使用正则表达式进行操作:

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

1

这是该问题的递归解决方案:

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
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.