Python index

The python index function is used to return the index position of the first occurrence of a specified string. The Python index function returns ValueError if the specified string not found.

In this section, we discuss how to write index Function in Python Programming with example. The index position of the index Function starts from 0, Not 1.

Python index Syntax

The syntax of the Python index function is

String_Value.index(Substring, Starting_Position, Ending_Position)
  • String_Value: Please select the valid String literal.
  • Substring: Please specify the string you want to search for.
  • Starting_Position: This is an optional parameter. If you want to specify the starting point (starting index position), then Please specify the index value here. If you omit this parameter, the index Function considers Zero as a starting position.
  • Ending_Position: This is an optional parameter. If you want to specify the endpoint (Ending index position), then Please specify an index value here. If you omit this parameter, the index Function considers the highest index number.

Python index method Example

The following set of examples help you understand the index Function.

# Python Index Method Example

Str1 = 'We are abc working at abc company';
Str2 = Str1.index('abc')
print('First Output of a Index() method is = ', Str2)

# Performing Index() function directly
Str3 = 'Find Tutorial at Tutorial Gateway'.index('Tutorial')
print('Second Output of a Index() method is = ', Str3)

# Using First Index while finding the String
Str5 = Str1.index('abc', 12)
print('Third Output of a Index() method is = ', Str5)

# Using First & Second Index while finding the String
Str6 = Str1.index('abc', 12, len(Str1) -1)
print('Fourth Output of a Index() method is = ', Str6)

# Using First & Second Index while finding Non existing String
Str7 = Str1.index('abc', 12, 21)
print('Fifth Output of a Index() method is = ', Str7)
Python Index

It finds the substring ‘abc’ inside the Str1 using index function and prints the output

Str2 = Str1.index('abc')
print('First Output of a Index() method is = ', Str2)

The index function in Python allows us to use index starting position. By specifying the starting index position, we can increase performance.

Str5 = Str1.index('abc', 12)
print('Third Output of a Index() method is = ', Str5)

The index function allows us to use Starting and ending indices. By specifying the starting and ending index positions, we can increase performance. The following String Method statement starts looking for ‘abc’ from index position 12.

Str6 = Str1.index('abc', 12, len(Str1) -1)
print('Fourth Output of a Index() method is = ', Str6)

The following Python statement is returning Value Error. Because the index function starts looking from 12 (means the first abc skipped) and ends at index position 21. As we all know, the second abc is in position 22.

Str7 = Str1.index('abc', 12, 21)
print('Fifth Output of a Index() method is = ', Str7)