English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriel de base Python

Contrôle de flux Python

Fonctions en Python

Types de données en Python

Opérations de fichiers Python

Objets et classes Python

Dates et heures Python

Connaissances avancées Python

Manuel de référence Python

Méthode d'utilisation et exemples de find() pour les chaînes de caractères Python

Python string methods

La méthode find() retourne l'indice de la première apparition de la sous-chaine (si elle est trouvée). Si elle n'est pas trouvée, elle retourne-1.

La syntaxe de la méthode find() est :

str.find(sub[, start[, end]])

paramètre find()

The find() method can use up to three parameters:

  • sub- It is the substring to be searched in the str string.

  • startandend (Optional)-Search for the substring str[start:end] in it

find() return value

The find() method returns an integer value.

  • If the substring is present in the string, it returns the index of the first occurrence of the substring.

  • If the substring is not present in the string, it returns-1.

Example1: find() without start and end parameters

quote = 'Let it be, let it be, let it be'
result = quote.find('let it')
print("Substring 'let it':", result)
result = quote.find('small')
print("Substring 'small':", result)
# How to use find()
if (quote.find('be,') != -1):
  print("Contains string 'be,'")
else:
  print("Not contained string")

When running the program, the output is:

Substring 'let it': 11
Substring 'small': -1
Contains string 'be,'

Example2: find() with start and end parameters

quote = 'Do small things with great love'
# Search for substring 'hings with great love'
print(quote.find('small things', 10))
# Search for substring ' small things with great love' 
print(quote.find('small things', 2))
# Search for substring 'hings with great lov'
print(quote.find('o small ', 10, -1))
# Search for substring 'll things with'
print(quote.find('things ', 6, 20))

When running the program, the output is:

-1
3
-1
9

Python string methods