This python function is used to return the index position of the first occurrence of a specified string. It returns ValueError if the specified text is not found.
In this section, we discuss how to write Python string index Function with an example and syntax is.
Str_Value.index(Substring, Starting_Position, Ending_Position)
The position of the Function starts from 0, Not 1.
- Substring: Please specify the text you want to search for.
- Starting_Position: This is an optional parameter. If you want to pass the beginning point, then Please specify the value here. If you omit this parameter, it considers Zero as a beginning position.
- Ending_Position: This is an optional parameter. If you want to provide the endpoint, then Please specify it here. If you omit this one, it considers the highest number.
Python index method Example
The following set of examples helps you understand it. The first statement finds the word ‘abc’ inside Str1 and prints the output.
The string index function allows us to use starting position. By providing the starting location, we can increase performance. So, let’s use the first position as 12
It also allows us to use Starting and ending values. In the nest line, we are passing the starting and ending locations. The following Method statement begins looking for ‘abc’ from 12 from ends at last.
The last Python statement is returning Value Error. Because the function begins looking from 12 (means the first abc skipped) and ends at 21. As we all know, the second abc is in position 22.
Str1 = 'We are abc working at abc company '; Str2 = Str1.index('abc') print('First Output of this is = ', Str2) # Performing directly Str3 = 'Find Tutorial at Tutorial Gateway'.index('Tutorial') print('Second Output is = ', Str3) # Using First point while finding Str5 = Str1.index('abc', 12) print('Third Output is = ', Str5) # Using First & Second argumenr while finding Str6 = Str1.index('abc', 12, len(Str1) -1) print('Fourth Output is = ', Str6) # Using First & Second finding while finding Non existing Str7 = Str1.index('abc', 12, 21) print('Fifth Output is = ', Str7)