Python String rfind ()

O método rfind () retorna o índice mais alto da substring (se encontrado). Se não for encontrado, retorna -1.

A sintaxe de rfind()é:

 str.rfind (sub (, início (, fim)))

Parâmetros rfind ()

rfind() método leva no máximo três parâmetros:

  • sub - é a substring a ser pesquisada na string str.
  • início e fim (opcional) - substring é pesquisado emstr(start:end)

Valor de retorno de rfind ()

rfind() método retorna um valor inteiro.

  • Se a substring existir dentro da string, ele retornará o índice mais alto onde a substring foi encontrada.
  • Se a substring não existir dentro da string, ele retornará -1.
Valor de retorno de rfind ()

Exemplo 1: rfind () sem argumento de início e fim

 quote = 'Let it be, let it be, let it be' result = quote.rfind('let it') print("Substring 'let it':", result) result = quote.rfind('small') print("Substring 'small ':", result) result = quote.rfind('be,') if (result != -1): print("Highest index where 'be,' occurs:", result) else: print("Doesn't contain substring")

Resultado

 Substring 'let it': 22 Substring 'small': -1 Contém substring 'be,'

Exemplo 2: rfind () com argumentos de início e fim

 quote = 'Do small things with great love' # Substring is searched in 'hings with great love' print(quote.rfind('things', 10)) # Substring is searched in ' small things with great love' print(quote.rfind('t', 2)) # Substring is searched in 'hings with great lov' print(quote.rfind('o small ', 10, -1)) # Substring is searched in 'll things with' print(quote.rfind('th', 6, 20))

Resultado

 -1 25 -1 18

Artigos interessantes...