O método rindex () retorna o índice mais alto da substring dentro da string (se encontrado). Se a substring não for encontrada, ele levantará uma exceção.
A sintaxe de rindex()
é:
str.rindex (sub (, start (, end)))
Parâmetros rindex ()
rindex()
método leva três parâmetros:
- sub - substring a ser pesquisada na string str.
- início e fim (opcional) - substring é pesquisado em
str(start:end)
Valor de retorno de rindex ()
- Se a substring existir dentro da string, ele retornará o índice mais alto na string onde a substring foi encontrada.
- Se a substring não existir dentro da string, ela gerará uma exceção ValueError .
rindex()
método é semelhante ao método rfind () para strings.
A única diferença é que rfind () retorna -1 se a substring não for encontrada, enquanto rindex () lança uma exceção.
Exemplo 1: rindex () sem argumento de início e fim
quote = 'Let it be, let it be, let it be' result = quote.rindex('let it') print("Substring 'let it':", result) result = quote.rindex('small') print("Substring 'small ':", result)
Resultado
Substring 'let it': 22 Traceback (última chamada mais recente): Arquivo "…", linha 6, em result = quote.rindex ('small') ValueError: substring não encontrada
Observação: o índice em Python começa em 0 e não em 1.
Exemplo 2: rindex () com argumentos de início e fim
quote = 'Do small things with great love' # Substring is searched in ' small things with great love' print(quote.rindex('t', 2)) # Substring is searched in 'll things with' print(quote.rindex('th', 6, 20)) # Substring is searched in 'hings with great lov' print(quote.rindex('o small ', 10, -1))
Resultado
25 18 Traceback (última chamada mais recente): Arquivo "…", linha 10, impresso (quote.rindex ('o small', 10, -1)) ValueError: substring não encontrada