[python] 문자열에서 마지막 부분 문자열 찾기, 대체

따라서 동일한 형식의 긴 문자열 목록이 있고 마지막 “.”을 찾고 싶습니다. 문자를 입력하고 “.-“로 바꿉니다. rfind를 사용해 보았지만 제대로 활용하지 못하는 것 같습니다.



답변

이것은 그것을해야한다

old_string = "this is going to have a full stop. some written sstuff!"
k = old_string.rfind(".")
new_string = old_string[:k] + ". - " + old_string[k+1:]


답변

오른쪽에서 교체하려면 :

def replace_right(source, target, replacement, replacements=None):
    return replacement.join(source.rsplit(target, replacements))

사용:

>>> replace_right("asd.asd.asd.", ".", ". -", 1)
'asd.asd.asd. -'


답변

정규식을 사용합니다.

import re
new_list = [re.sub(r"\.(?=[^.]*$)", r". - ", s) for s in old_list]


답변

하나의 라이너는 다음과 같습니다.

str=str[::-1].replace(".",".-",1)[::-1]


답변

오른쪽에서 처음 나오는 단어를 대체하는 아래 기능을 사용할 수 있습니다.

def replace_from_right(text: str, original_text: str, new_text: str) -> str:
    """ Replace first occurrence of original_text by new_text. """
    return text[::-1].replace(original_text[::-1], new_text[::-1], 1)[::-1]


답변

a = "A long string with a . in the middle ending with ."

# 문자열의 마지막 발생 인덱스를 찾으려면 우리의 경우 # with 마지막 발생의 인덱스를 찾습니다.

index = a.rfind("with") 

# 인덱스가 0부터 시작하므로 결과는 44가됩니다.


답변

순진한 접근 방식 :

a = "A long string with a . in the middle ending with ."
fchar = '.'
rchar = '. -'
a[::-1].replace(fchar, rchar[::-1], 1)[::-1]

Out[2]: 'A long string with a . in the middle ending with . -'

Aditya Sihag의 대답은 다음과 rfind같습니다.

pos = a.rfind('.')
a[:pos] + '. -' + a[pos+1:]