it-source

rreplace - 문자열에서 마지막으로 나타나는 식을 바꾸는 방법은 무엇입니까?

criticalcode 2023. 6. 15. 21:54
반응형

rreplace - 문자열에서 마지막으로 나타나는 식을 바꾸는 방법은 무엇입니까?

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

다음은 한 줄로 된 것입니다.

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

오래된 하위 문자열이 모두 새 문자열로 대체된 문자열 복사본을 반환합니다.번째 maxreplace 항목이 바뀝니다.

사용 중인 전체 예:

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

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

저는 이것이 가장 효율적인 방법이라고 생각하지 않을 것입니다. 하지만 이것은 간단한 방법입니다.문제의 모든 문자열을 반전시키고 다음을 사용하여 일반적인 교체를 수행합니다.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>'

문자열을 역방향으로 바꾸고 첫 번째 항목을 바꾼 후 다시 역방향으로 바꾸기만 하면 됩니다.

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.

'old' 문자열에 특수 문자가 포함되어 있지 않은 경우 정규식을 사용할 수 있습니다.

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

다음은 문제에 대한 재귀적인 해결책입니다.

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

사용해 보십시오.

def replace_last(string, old, new):
    old_idx = string.rfind(old)
    return string[:old_idx] + new + string[old_idx+len(old):]

마찬가지로 string.rfind()를 string.find()로 대체하여 첫 번째 항목을 바꿀 수 있습니다.

도움이 되길 바랍니다.

문자열 목록이 있으면 목록 이해와 문자열 슬라이싱을 하나의 라이너로 사용하여 전체 목록을 커버할 수 있습니다.기능을 사용할 필요가 없습니다.

myList = [x[::-1].replace('<div>'[::-1],'<bad>'[::-1],1)[::-1] if x.endswith('<div>') else x for x in myList]

교체 기준에 맞지 않는 항목을 목록에 보관할 경우 사용합니다. 그렇지 않으면 목록이 기준에 맞는 항목이 됩니다.

언급URL : https://stackoverflow.com/questions/2556108/rreplace-how-to-replace-the-last-occurrence-of-an-expression-in-a-string

반응형