【问题标题】:rreplace - How to replace the last occurrence of an expression in a string?replace - 如何替换字符串中最后一次出现的表达式?
【发布时间】:2011-02-03 02:35:59
【问题描述】:

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

【问题讨论】:

  • 好问题,从这样一个简单问题的复杂解决方案来看。
  • 下面的答案中有一个优雅的单行字,花了 9 年(!)才被添加到这个问题中,只需向下滚动即可找到它。

标签: python string


【解决方案1】:

这是一个单行

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

返回字符串 s 的副本,其中所有出现的子字符串 old 都替换为 new。第一个 maxreplace 次出现被替换。

还有一个完整的示例在使用中:

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

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

【讨论】:

  • 不错!用它从行中删除尾随逗号:line = "".join(line.rsplit(",", 1)),同时保留填充空间。
  • 这里可以修改什么以在数据框列上使用它?
【解决方案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.

【讨论】:

  • 当我使用它时,数字书页的格式从未改变,而使用'join'功能改变了格式。太棒了!
【解决方案3】:

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

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

【讨论】:

    【解决方案4】:

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

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

      【讨论】:

      • 非常好!在我的程序(> 500 个字符)中替换典型字符串中最后一次出现的表达式的不科学基准测试中,您的解决方案比 Alex 的解决方案快三倍,比 Mark 的解决方案快四倍。感谢大家的回答!
      • 谢谢,它有效。 .replace 方法采用第三个可选参数“count”,告诉它替换前 n 次出现。如果这需要一个-1,那不是很直观,但不幸的是它不会,所以我们需要你的解决方案。
      【解决方案6】:

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

      【讨论】:

        猜你喜欢
        • 2011-09-10
        • 2011-04-19
        • 2020-03-18
        • 2011-07-26
        • 1970-01-01
        • 2015-05-25
        • 2021-04-29
        • 1970-01-01
        相关资源
        最近更新 更多