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>'
Run Code Online (Sandbox Code Playgroud)
mg.*_*mg. 168
>>> 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'
Run Code Online (Sandbox Code Playgroud)
Joh*_*n D 36
这是一个单行:
result = new.join(s.rsplit(old, maxreplace))
Run Code Online (Sandbox Code Playgroud)
返回字符串s的副本,其中所有出现的子字符串old 都被new替换。第一个maxreplace出现被替换。
以及使用中的完整示例:
s = 'mississipi'
old = 'iss'
new = 'XXX'
maxreplace = 1
result = new.join(s.rsplit(old, maxreplace))
>>> result
'missXXXipi'
Run Code Online (Sandbox Code Playgroud)
Joe*_*Joe 13
只需反转字符串,替换第一次出现并再次反转它:
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)
Run Code Online (Sandbox Code Playgroud)
输出:
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.
Run Code Online (Sandbox Code Playgroud)
Mar*_*ers 12
我不会假装这是最有效的方法,但这是一种简单的方法.它会反转所有相关字符串,使用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>'
Run Code Online (Sandbox Code Playgroud)
如果您知道“旧”字符串不包含任何特殊字符,您可以使用正则表达式:
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>'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
63015 次 |
| 最近记录: |