Python3 index() Method

Python3 字符串Python3 Strings


Description

The index() method detects whether the string contains the substring str. If the range beg (start) and end (end) is specified, it checks whether the substring is contained within the specified 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

Syntax of the index() method:

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

Parameters

  • str -- The string to search for
  • beg -- Starting index, defaults to 0.
  • end -- Ending index, defaults to the length of the string.

Return Value

If the substring is contained, the starting index value is returned; otherwise, an exception is raised.

Example

The following example demonstrates the index() method:

#!/usr/bin/python3

str1 = "Example 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 will appear if 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 following chapters, we will introduce the use of Python Exception in detail.


Python3 字符串Python3 Strings

Other Extensions