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 rindex() sur les chaînes de caractères Python

Python string methods

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]])

paramètres de rindex()

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]

valeur de retour de rindex()

  • 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.

Example1: rindex() without start and end parameters

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.

Example2: rindex() with start and end parameters

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

Python string methods