Latest web development tutorials

Python index () method

Python strings Python strings


Python index () method to detect whether a string contains a substring str, if you specify beg (start) and end (end) range, it is checked whether contained within the specified range, the method and python find () method, in that it If the string str is not an exception will be reported.


index () method syntax:

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


  • str - the specified search string
  • beg - starting index, the default is 0.
  • end - the end of the index, the default is the length of the string.

return value

If you include substring returns the index value at the start, otherwise it throws an exception.


The following example shows the index () instance method:


str1 = "this is string!!!";
str2 = "exam";

print str1.index(str2);
print str1.index(str2, 10);
print str1.index(str2, 40);

Examples of the above output results are as follows:

Traceback (most recent call last):
  File "", line 8, in 
  print str1.index(str2, 40);
ValueError: substring not found

shell returned 1

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

Python strings Python strings