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

时间:2010-03-31 20:07:24

标签: python string

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

6 个答案:

答案 0 :(得分:148)

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

答案 1 :(得分:10)

我不会假装这是最有效的方式,但这是一种简单的方法。它会反转所有相关的字符串,在反向字符串上使用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>'

答案 2 :(得分:4)

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

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

答案 3 :(得分:2)

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

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.

答案 4 :(得分: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

答案 5 :(得分:1)

这里是单线:

if(mysqli_num_rows($result_1)>0)
{

}
  

返回字符串 s 的副本,并将所有出现的子字符串 old 替换为 new 。最早的 maxreplace 出现。

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

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