Latest web development tutorials

Python3 index () method

Python3 string Python3 string


description

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 of the same, but if str string is not an exception will be reported.

grammar

index () method syntax:

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

parameter

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

Examples

The following example shows the index () instance method:

#!/usr/bin/python3

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

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

Examples of the above output results are as follows (information will be abnormal not found):

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


Python3 string Python3 string