Easy Tutorial
❮ Python Func Oct Ref Math Tan ❯

Python3 index() Method

Python3 Strings


Description

The index() method checks if the string contains the substring str. If the beg (start) and end (end) ranges are specified, it checks if it is included within that range. This method is similar to the Python find() method, except that it raises an exception if str is not found in the string.

Syntax

The syntax for the index() method is:

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

Parameters

Return Value

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

Example

The following example demonstrates the index() method:

#!/usr/bin/python3

str1 = "tutorialpro 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 (with exceptions for unfound substrings):

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

Note: In the next few sections, we will detail the use of Python Exceptions.


Python3 Strings

❮ Python Func Oct Ref Math Tan ❯