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

Utilisation et exemples de la méthode index() de la chaîne de caractères Python

Python string methods

La méthode index() retourne l'indice de la sous-chaîne dans la chaîne (si elle est trouvée). Si la sous-chaîne n'est pas trouvée, une exception est levée.

ChaîneLa syntaxe de la méthode index() est :

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

Paramètres de index()

La méthode index() prend trois paramètres :

  • sous  -la sous-chaîne à chercher dans la chaîne de caractères str.

  • débutetfin(optionnel)-在str [start:end]中str [start:end]中

Search for substring

  • index() return value

  • If the substring exists in the string, it will return the smallest index of the substring found in the string.If the substring does not exist in the string, it will raiseValueError

exception.index() method is similar toPython indexing starts from 0, not

string's find() method-1The only difference is that, if the substring is not found, the find() method returns

:index() with start and end parameters1,while index() raises an exception.

Example
:index() with only substring parameter
result = sentence.index('is fun')
print('Substring 'is fun':', result)
result = sentence.index('Java')

When running this program, the output is:

print('Substring 'Java':', result) 19
Traceback (most recent call last):
  File "...", line 6Substring 'is fun':
ValueError: substring not found

, inresult = sentence.index('Java') Note:1Python indexing starts from 0, not

:index() with start and end parameters2.

Example
sentence = 'Python programming is fun.'
# Search for substring 'gramming is fun.' 10))
# Search for substring 'gramming is '
# Search for substring 'g is' 10, -4))
# Search for substring 'programming'
print(sentence.index('fun', 7, 18))

When running this program, the output is:

15
17
Traceback (most recent call last):
  File "...", line 10, inprint(quote.index('fun', 7, 18))
ValueError: substring not found

Python string methods