Python index() Method

Python 字符串Python String


Description

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

Syntax

index() method syntax:

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

Parameters

  • substring -- The string to search for.
  • beg -- The starting index, default is 0.
  • end -- The ending index, default is the length of the string.

Return Value

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

Examples

The following example demonstrates the index() method:

Example (Python 2.0+)

#!/usr/bin/python str1 = "this is string example....wow!!!" str2 = "exam" print str1.index(str2) print str1.index(str2, 10) print str1.index(str2, 40)

The output of the above example is:

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

shell returned 1

Note:In the following sections, we will introduce the use of Python Exception in detail.


Python 字符串Python String

Other Extensions