Python index() method


The Python index() method detects whether a string contains the substring str or not (It checks whether it contains the string).

By default it starts searching from index 0, but you can set the start and index as parameters.

Related course: Complete Python Programming Course & Exercises

syntax

str.index(str, beg=0, end=len(string))

parameters

  • str - Specifies the string to be retrieved
  • beg - starts the index, default is 0.
  • end - end index, default is the length of the string

return value

  • Returns the starting index value if the substring is included, otherwise throws an exception

index() example

By calling the index() method on a string, it returns the position of the substring.

#!/usr/bin/python

str1 = "this is string example... .wow!!!" ;
str2 = "example";
print(str1.index(str2))
print(str1.index(str2, 10))
print(str1.index(str2, 40))

Results.

15
15
Traceback (most recent call last):
  File "test.py", line 8, in 
  print str1.index(str2, 40);
ValueError: substring not found
shell returned 1

example 2

When looking for an element in a list, you can use the index value (position). To get the position call the index() method

index() syntax.

list.index(obj)

Code example:

A = [123, 'alice', 'zara', 'bella']
print(A.index('alice')) 
# Result: 1

print(A.index('gina'))
# Error: ValueError: 'gina' is not in list

example 3

The index() function returns the first occurence found. In the example below the letter 'l' occurs several times:

>>> a = "hello world"
>>> a.index('h')
0
>>> a.index('e')
1
>>> a.index('l')
2
>>> a.index('o')
4
>>>