Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python3 index() Method

Python3 index() Method

Python3 Strings Python3 Strings


Description

The index() method checks whether a string contains the substring str; if the beg (start) and end ranges are specified, it checks within that range. This method is the same as the Python find() method, except that it raises an exception if str is not in the string.

Syntax

index() method syntax:


str.index(str, beg=0, end=len(string))

Parameters

Return Value

Returns the starting index if the substring is contained, otherwise raises an exception.

Example

The following example demonstrates the index() method:


#!/usr/bin/python3

str1 = "Runoob example....wow!!!"
str2 = "exam";

print (str1.index(str2))
print (str1.index(str2, 5))
print (str1.index(str2, 10))

The output of the above example is as follows (an exception message appears when not found):


7
7
Traceback (most recent call last):
  File "test.py", line 8, in 
    print (str1.index(str2, 10))
ValueError: substring not found

**Note:** In the next few chapters we will cover the use of Python Exception in detail.


Python3 Strings Python3 Strings