How To Use Python rindex() Method With Example

The python rindex() method returns the index position of the last occurrence of the substring in the string. This method is the same as the rfind() method, except that an exception will be reported if the substring is not in the string.

1. Grammar.

  1. The rindex() method syntax.
    parent_sting.rindex(sub_string[,start=0[,end=len(S)]])
  2. Parameters.
    sub_string -- Specifies the substring to retrieve.
    parent_string -- Parent string.
    start -- Optional parameter. The location to start searching. The default value is 0. (can be specified separately)
    end -- Optional parameter. End search position. The default is the length of the string. (cannot be specified separately)
  3. Return value: Returns the index position of the last occurrence of the substring in the string. If there is no match, an exception will be reported.

2. Python rindex() Example.

  1. The following example shows how to use the rindex() method.
    >>> str_1 = "I love python"
    >>>
    >>> # define the second string.
    >>> str_2 = "love"
    >>>
    >>> print (str_1.rindex(str_2))
    2
    >>> print (str_1.rindex(str_2,10))
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: substring not found

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Clicky