파이썬 find 함수 메소드 rfind 쓰지 않고 마지막 문자열 하나만 찾기

조회수 1868회
def findLast(filename,key):

    infile = open(filename,"r")  
    outfile = open("result.txt","w")
    text = infile.read()
    position = text.find(key)
    if position == -1:
        outfile.write(key + " is not found.\n")
    else:
        outfile.write(key + " is at " + str(position) + ".\n")
    outfile.close()
    infile.close()
    print("Done")

위 함수는 첫 번째 문자열만 찾는 함수입니다. 혹시 여기서 while 함수를 사용해서 마지막 문자열만 찾는 함수는 어떻게 만들 수 있을까요 ㅠ

1 답변

  • >>> help('s'.find)
    Help on built-in function find:
    
    find(...) method of builtins.str instance
        S.find(sub[, start[, end]]) -> int
    
        Return the lowest index in S where substring sub is found,
        such that sub is contained within S[start:end].  Optional
        arguments start and end are interpreted as in slice notation.
    
        Return -1 on failure.
    
    >>> text = 'ab ab cd ab cd ab ab ac ab af'
    >>> text.find('ab')
    0
    >>> text.find('ab', 1)
    3
    >>> text.find('ab', 4)
    9
    >>> text.find('ab', 10)
    15
    >>> text.find('ab', 16)
    18
    >>> text.find('ab', 19)
    24
    >>> text.find('ab', 25)
    -1
    >>> text[24:]
    'ab af'
    

    find 메소드는 찾기를 시작할 인덱스를 줄 수 있습니다. 그래서, 찾기가 성공하면, 시작인덱스를 찾은 인덱스보다 1 큰 값으로 주기를 반복하면서, -1을 반환할 때까지 반복하면, -1이 나오기 전의 인덱스가 마지막에 일치하는 위치가 됩니다. 이걸while 루프 안에서 반복하면 되겠습니다.

    def find_last(text, key):
        start_index = 0
        last_found_index = -1
        while True:
            i = text.find(key, start_index)
            if i == -1:
                break
            last_found_index = i
            start_index = i+1
        return last_found_index
    

    좀 더 잘하려면, findend 인자까지 활용하여, 바이너리 서치를 해 나가는 방법도 있을 것 같습니다.

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)