【问题标题】:Replace items from the back of a string从字符串后面替换项目
【发布时间】:2021-07-03 20:46:31
【问题描述】:

我想替换字符串末尾的几个匹配项。我试过这个:

replace_me="<!doctype html><html><body><p>hello</p></body></html>"
print('replacing 3 matches of > from back of string. please wait...')
replace_me.replace('>','&gt;',-1)
print(replace_me)

但它给了我无法替代的输出:&lt;!doctype html&gt;&lt;html&gt;&lt;body&gt;&lt;p&gt;hello&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;

Complete Output

是否甚至可以替换最后几次出现的字符串?

【问题讨论】:

  • 几个?几是几?
  • @BuddyBoblll 我的意思是,比如说,从后面出现 3 次。
  • 哦,好吧,哈哈
  • 你想要的输出是什么?

标签: python string replace


【解决方案1】:

如果你从后面替换,你可以翻转字符串并用你的反向匹配替换它来替换 N 次出现:

replace_me="<!doctype html><html><body><p>hello</p></body></html>" 
N=3 
newstr = '&gt;'[::-1]
replace_me_new = replace_me[::-1].replace('>',newstr,N)[::-1]
print(replace_me_new)

哪个输出:

<!doctype html><html><body><p>hello</p&gt;</body&gt;</html&gt;

以模仿str.replace()的方式进行概括:

def rreplace(s, old, new, count=-1):
    return s[::-1].replace(old[::-1], new[::-1], count)[::-1]

【讨论】:

  • reversed(s) 不会比s[::-1] 更清晰吗?
  • 好主意!您还可以反转匹配以获得一般解决方案:def rreplace(s, old, new, count=-1): return s[::-1].replace(old[::-1], new[::-1], count)[::-1].
  • @PatrickParker: reversed() 是一个迭代器,在您执行''.join(reversed(...)) 之类的操作之前不会返回新序列。另外,'reversed' object has no attribute 'replace'.
【解决方案2】:
def replace_last(a, b, s, n=1):
    for _ in range(n):
        i = s.rindex(a)
        s = s[0:i] + b + s[i+len(a):]
    return s

用法:

>>> replace_last('>', '&gt;', "<!doctype html><html><body><p>hello</p></body></html>", n=3)
'<!doctype html><html><body><p>hello</p&gt;</body&gt;</html&gt;'

【讨论】:

  • 我更喜欢@jhso 的解决方案:它可以让内置的str.replace() 处理极端情况,例如当匹配的模式包含替换时——我的解决方案绝对不能处理。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-26
  • 1970-01-01
  • 1970-01-01
  • 2014-11-26
  • 2016-01-31
相关资源
最近更新 更多