Metoda find () zwraca indeks pierwszego wystąpienia podciągu (jeśli został znaleziony). Jeśli nie zostanie znaleziony, zwraca -1.
Składnia find()
metody to:
str.find (sub (, start (, koniec)))
Parametry metody find ()
find()
Metoda ta maksymalnie trzy parametry:
- sub - jest to podciąg do wyszukania w ciągu znaków.
- początek i koniec (opcjonalnie) - zakres,
str(start:end)
w którym przeszukiwany jest podciąg.
Wartość zwracana z metody find ()
find()
Sposób powraca liczbę całkowitą:
- Jeśli podciąg istnieje wewnątrz ciągu, zwraca indeks pierwszego wystąpienia podłańcucha.
- Jeśli podciąg nie istnieje w ciągu, zwraca -1.
Działanie metody find ()

Przykład 1: find () bez argumentu początku i końca
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")
Wynik
Podłańcuch „niech to”: 11 Podłańcuch „mały”: -1 Zawiera podłańcuch „be,”
Przykład 2: find () Z argumentami start i end
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))
Wynik
-1 3 -1 9