Python index() method
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
- substring -- the string to search for.
- beg -- the starting index, defaulting to 0.
- end -- the ending index, defaults to the length of the string.
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
"
str1
.
index
(
str2
)
str1
.
index
(
str2
,
10
)
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