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