Python String index()
Python String index() method returns the index of first occurrence of specified value in given string.
We can also specify the bounds in the strings, in which the search for the given value has to happen, via start and end parameters.
If the value is not present in this string, index() returns raises ValueError. In fact, this behavior is the only difference between str.index() method and str.find() method.
In this tutorial, we will learn the syntax and examples for index() method of String class.
Syntax
The syntax of String index() method in Python is
str.index(value, start, end)
where
Parameter | Required/ Optional | Description |
---|---|---|
value | Required | A string. Index of first occurrence of this value in the string has to be returned. |
start | Optional | An integer. The index from which, the value has to be searched in this string. |
end | Optional | An integer. The index until which, the value has to be searched in this string. |
Examples
index() with Default Parameter Values
In the following program, we take a string 'abcd-abcd-abcd'
in x
, and find the index of the value 'bc'
in the string x
.
Example.py
x = 'abcd-abcd-abcd'
value = 'cd'
result = x.index(value)
print("Index :", result)
Output
Index : 2
Explanation
'a b c d - a b c d - a b c d'
0 1 2 3 4 5 6 7 8 9 . . .
c d : index of 'cd' is 2
The index of first occurrence of value 'cd'
is 2.
Even though there are multiple occurrences of the value in this string, index() method returns only the index of first occurrence.
index() with Value not in String
We already know that index() raises a ValueError if the specified value is not present in the string.
Example.py
x = 'abcd-abcd-abcd'
value = 'xy'
result = x.index(value)
print("Index :", result)
Output
Traceback (most recent call last):
File "d:/workspace/python/example.py", line 3, in <module>
result = x.index(value)
ValueError: substring not found
index() with Specific Start
In the following program, we will specify a starting position/index from which the search for the value value in the string has to happen.
Example.py
x = 'abcd-abcd-abcd'
value = 'cd'
start = 5
result = x.index(value, start)
print("Index :", result)
Output
Index : 7
Explanation
'a b c d - a b c d - a b c d'
0 1 2 3 4 5 6 7 8 9 10 . .
|
start=5 from this position
c d : index of 'cd' is 7
index() with Specific Start and End
In the following program, we will specify a starting position/index from which the search for the value value in the string has to happen and the end position up until which the search for value in the string has to happen.
Example.py
x = 'abcd-abcd-abcd'
value = 'cd'
start = 5
end = 9
result = x.index(value, start, end)
print("Index :", result)
Output
Index : 7
Conclusion
In this Python Tutorial, we learned how to find the index of first occurrence of specified value in given string, using String method – index().