Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python index() method

Python index() method

Python Strings Python Strings


Description

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

Syntax

index() method syntax:


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

Parameters

Return Value

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

Example

The following example shows how to use 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 next few chapters, we will introduce the use of Python Exception in detail.


Python Strings Python Strings