Il metodo find () restituisce l'indice della prima occorrenza della sottostringa (se trovata). Se non viene trovato, restituisce -1.
La sintassi del find()
metodo è:
str. ricerca (sub (, inizio (, fine)))
Parametri per il metodo find ()
Il find()
metodo accetta al massimo tre parametri:
- sub - È la sottostringa da cercare nella stringa str.
- inizio e fine (facoltativo): l'intervallo
str(start:end)
all'interno del quale viene eseguita la ricerca della sottostringa.
Valore restituito dal metodo find ()
Il find()
metodo restituisce un valore intero:
- Se la sottostringa esiste all'interno della stringa, restituisce l'indice della prima occorrenza della sottostringa.
- Se la sottostringa non esiste all'interno della stringa, restituisce -1.
Utilizzo del metodo find ()

Esempio 1: find () senza argomento iniziale e finale
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")
Produzione
Sottostringa 'let it': 11 Sottostringa 'small': -1 Contiene sottostringa 'be,'
Esempio 2: find () con argomenti di inizio e fine
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))
Produzione
-1 3-1 9