Najdi Python String ()

Metoda find () vrne indeks prvega pojavljanja podniza (če je najden). Če ni najden, vrne -1.

Sintaksa find()metode je:

 str.find (sub (, začetek (, konec)))

Parametri metode find ()

find()Postopek traja največ tri parametre:

  • sub - To je podniz, ki ga je treba iskati v nizu str.
  • začetek in konec (neobvezno) - obseg, str(start:end)v katerem se išče podniz.

Vrnjena vrednost iz metode find ()

find()Postopek vrne vrednost celo število:

  • Če podniz obstaja znotraj niza, vrne indeks prve pojavitve podniza.
  • Če podniz ne obstaja znotraj niza, vrne -1.

Delovanje metode find ()

Delovanje metod find () in rfind () Pythona

Primer 1: find () Brez argumenta brez začetka in konca

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

Izhod

 Podniz 'pusti': 11 Podniz 'majhen': -1 Vsebuje podniz 'be,'

Primer 2: find () Z začetkom in koncem Argumenti

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

Izhod

 -1 3 -1 9

Zanimive Članki...