String Python find ()

O método find () retorna o índice da primeira ocorrência da substring (se encontrada). Se não for encontrado, retorna -1.

A sintaxe do find()método é:

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

Parâmetros para o método find ()

O find()método aceita no máximo três parâmetros:

  • sub - É a substring a ser pesquisada na string str.
  • início e fim (opcional) - O intervalo str(start:end)no qual a substring é pesquisada.

Valor de retorno do método find ()

O find()método retorna um valor inteiro:

  • Se a substring existir dentro da string, ele retornará o índice da primeira ocorrência da substring.
  • Se a substring não existir dentro da string, ele retornará -1.

Trabalho do método find ()

Trabalho dos métodos find () e rfind () da string Python

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

 quote = 'Let it be, let it be, let it be' # first occurance of 'let it'(case sensitive) result = quote.find('let it') print("Substring 'let it':", result) # find returns -1 if substring not found result = quote.find('small') print("Substring 'small ':", result) # How to use find() if (quote.find('be,') != -1): print("Contains substring 'be,'") else: print("Doesn't contain substring")

Resultado

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

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

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

Resultado

 -1 3 -1 9

Artigos interessantes...