English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
La méthode rindex() recherche une valeur spécifiée dans une chaîne et retourne la dernière position où elle est trouvée. Si la sous-chaine n'est pas trouvée, une exception est levée.
La syntaxe de rindex() est :
str.rindex(sub[, start[, end]])
La méthode rindex() utilise trois paramètres :
sub -sous-chaine à rechercher dans la chaîne str.
startetend(optionnel)-recherche de la sous-chaine dans str[start:end]
If the substring exists in the string, it will return the last position found in the string containing the substring.
If the substring does not exist in the string, it will raiseValueErrorexception.
rindex() method is similar tostring's rfind() method.
The only difference is that rfind() returns-1, and rindex() will raise an exception.
quote = 'Let it be, let it be, let it be' result = quote.rindex('let it') print("Substring 'let it':", result) result = quote.rindex('small') print("Substring 'small':", result)
When running this program, the output is:
Substring 'let it': 22 Traceback (most recent call last): File "...", line 6, in <module> result = quote.rindex('small') ValueError: substring not found
Note: In Python, indexing starts from 0, not1.
quote = 'Do small things with great love' # Search for the substring ' small things with great love' print(quote.rindex('t', 2)) # Search for the substring 'll things with' print(quote.rindex('th', 6, 20)) # Search for the substring 'hings with great lov' print(quote.rindex('o small ', 10, -1))
When running this program, the output is:
25 18 Traceback (most recent call last): File "...", line 10, in <module> print(quote.rindex('o small ', 10, -1)) ValueError: substring not found