Similar to the find () method, the index () method can also be used to retrieve whether the specified string is included. The difference is that when the specified string does not exist, the index() method will throw an exception.
The syntax of the index() method is as follows:
str.index(sub[,start[,end]])
The meaning of each parameter in this format is:
[Example] Use index () method to retrieve the index of the first occurrence of "e" in "www.freelearningpoints.com".
string = "www.freelearningpoints.com" string.index('e')
The output is:
6
[Example] When the retrieval fails, index() will throw an exception.
string = "www.freelearningpoints.com" string.index('b')
The output is:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
[ipython-input-1-150698d84fad] in [module]
1 string = "www.freelearningpoints.com"
----> 2 string.index('b')
ValueError: substring not found
Like find() and rfind(), string variables also have rindex() methods, which are similar to index() methods, except that they are retrieved from the right, for example:
string = "www.freelearningpoints.com" string.rindex('e')
The output is:
9
More Tutorials:
Python Installation - Linux (Ubuntu)More Python Exercises:
Python String Exercises