Python - String Method - index() Tutorial
It will return the index of the first occurrence of the specified value in the given string. If not found it will raise an exception. It is similar to find(), the only difference is find() method will return -1 if the specified value is not found.
Syntax-
String.index(value, start, end)
#value - It is a specified value that
needs to be searched in the given String.
#start - (Optional) It is a position to start
the search, by default, it is 0
#end - (Optional) It is a position to end search,
by default is the end of the string
Example-
str1 = "Hello Welcome to python Tutorial"
print(str1.index("python"))
print(str1.index("to",10,30))
print(str1.index("to",10,13))
print(str1.index("Python"))#case sensitive
Output-
17
14
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_6136/1803055335.py in <module>
2 print(str1.index("python"))
3 print(str1.index("to",10,30))
----> 4 print(str1.index("to",10,13))
5 print(str1.index("Python"))#case sensitive
ValueError: substring not found