Python String rfind ()

Il metodo rfind () restituisce l'indice più alto della sottostringa (se trovato). Se non viene trovato, restituisce -1.

La sintassi di rfind()è:

 str.rfind (sub (, start (, end)))

Parametri rfind ()

rfind() il metodo accetta un massimo di tre parametri:

  • sub - È la sottostringa in cui cercare nella stringa str.
  • inizio e fine (opzionale) - la sottostringa viene cercata all'interno distr(start:end)

Valore restituito da rfind ()

rfind() il metodo restituisce un valore intero.

  • Se la sottostringa esiste all'interno della stringa, restituisce l'indice più alto in cui si trova la sottostringa.
  • Se la sottostringa non esiste all'interno della stringa, restituisce -1.
Valore restituito da rfind ()

Esempio 1: rfind () senza argomento iniziale e finale

 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")

Produzione

 Sottostringa 'let it': 22 Sottostringa 'small': -1 Contiene sottostringa 'be,'

Esempio 2: rfind () con argomenti di inizio e fine

 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))

Produzione

 -1 25-1 18

Articoli interessanti...