Python String Method – index()

Spread the love

index() Method –

The index method returns the index of a substring in a string. If not found then it raises an exception.

Syntax –

string.index(sub, start, end)

sub – the substring that you want to search.

start – start index from where the search should begin.

end – the end index before which the search should end.

Example –

In [1]: string = 'python is cool. I love python.'

In [2]: string.index('python')
Out[2]: 0

In [3]: string.index('java')
Traceback (most recent call last):

  File "C:\Users\BHOLA\AppData\Local\Temp\ipykernel_13920\821294200.py", line 1, in <cell line: 1>
    string.index('java')

ValueError: substring not found

Index with start and end arguments –

In [4]: string.index('python', 10, -1)
Out[4]: 23

Related Posts –

  1. Python String Method – Capitalize()
  2. Python String Method – title()
  3. Python String Method – center()
  4. Python String Method – count()
  5. Python String Method – startswith()
  6. Python String Method – endswith()
  7. Python String Method – find()

Rating: 1 out of 5.

Leave a Reply