La méthode find () renvoie l'index de la première occurrence de la sous-chaîne (si elle est trouvée). S'il n'est pas trouvé, il renvoie -1.
La syntaxe de la find()
méthode est:
str.find (sous (, début (, fin)))
Paramètres de la méthode find ()
La find()
méthode prend au maximum trois paramètres:
- sub - C'est la sous-chaîne à rechercher dans la chaîne str.
- début et fin (facultatif) - La plage
str(start:end)
dans laquelle la sous-chaîne est recherchée.
Valeur renvoyée par la méthode find ()
La find()
méthode renvoie une valeur entière:
- Si la sous-chaîne existe à l'intérieur de la chaîne, elle renvoie l'index de la première occurrence de la sous-chaîne.
- Si la sous-chaîne n'existe pas dans la chaîne, elle renvoie -1.
Fonctionnement de la méthode find ()

Exemple 1: find () sans argument de début et de fin
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")
Production
Substring 'let it': 11 Substring 'small': -1 Contient la sous-chaîne 'be,'
Exemple 2: find () avec les arguments de début et de fin
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))
Production
-1 3 -1 9