It determines if string str occurs in string or in a substring of string if starting index beg and ending index end are given. This method is same as find(), but raises an exception if sub is not found.
The syntax of the method is: str.index(str, Start = 0 end = len(string))
Key Points :
• If there is no substring within the string, this method raises an exception.
• This function returns the index of the value we search for in a string for the first occurrence.
• In the scenario that the substring does not occur within a string, raise ValueError Exception.
We’ll be covering the following topics in this tutorial:
index() Parameters
The three parameters of the index() are defined below:
str: This is a mandatory parameter that is used to define the searchable value.
start: This is an optional parameter that is used to determine the start of the search; its default is 0.
end: This is an optional parameter used to signify where the search should end. The default is at the end of the string.
Return Value from index()
This method returns the values as follows:
• The first place of the substring identified is returned by this method.
• The ValueError exception would be raised if the substring is not found.
Python String find() vs Python String index()
All these methods are the same, but in case the substring does not occur in the string, there is a major difference:
• If we use the find() python method, it returns -1.
• If we use the python index(), on the other side, it will raise the ValueError Exception.
Below is the python program to demonstrate the index() function:
str_a = "The Best Learning Resource for Online Education"; str_b = "Online"; print (str_a.index(str_b)) print (str_a.index(str_b, 10)) print (str_a.index(str_b, 40))
When we run above the program, the outcome is as follows:
31
31
Traceback (most recent call last):
File “main.py”, line 5, in <module>
print (str_a.index(str_b, 40))
ValueError: substring not found
Below are several other functions that we can use to work with string in Python 3