English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
rindex() 메서드는 문자열에서 지정된 값을 검색하고, 발견된 마지막 위치를 반환합니다. 서브 문자열이 발견되지 않으면 예외가 발생합니다。
rindex()의 문법은 다음과 같습니다:
str.rindex(sub[, start[, end]])
rindex() 메서드는 세 가지 매개변수를 사용합니다:
sub -str 문자열에서 검색할 서브 문자열을 입력하세요。
start과end(선택)-str[start:end] 내에서 서브 문자열을 검색
문자열에 서브스트링이 존재하면, 그 서브스트링이 발견된 문자열의 마지막 위치를 반환합니다。
서브스트링이 문자열에 존재하지 않으면ValueError예외
rindex() 메서드는string의 rfind() 메서드。
결별적인 차이는 rfind()가 서브스트링을 찾지 못하면-1,rindex()는 예외를 발생시킵니다。
quote = 'Let it be, let it be, let it be' result = quote.rindex('let it') print("서브스트링 'let it':", result) result = quote.rindex('small') print("서브스트링 'small ':", result)
이 프로그램을 실행할 때, 출력은 다음과 같습니다:
서브스트링 'let it': 22 Traceback (most recent call last): File "...", line 6, in <module> result = quote.rindex('small') ValueError: 서브스트링을 찾을 수 없음
주의: 파이썬에서 인덱스는 0부터 시작하지 않습니다1。
quote = 'Do small things with great love' # 'small things with great love' 서브스트링을 검색 print(quote.rindex('t', 2)) # 'll things with' 서브스트링을 검색 print(quote.rindex('th', 6, 20)) # 'hings with great love' 서브스트링을 검색 print(quote.rindex('o small ', 10, -1))
이 프로그램을 실행할 때, 출력은 다음과 같습니다:
25 18 Traceback (most recent call last): File "...", line 10, in <module> print(quote.rindex('o small ', 10, -1)) ValueError: 서브스트링을 찾을 수 없음