
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 –
- Python String Method – Capitalize()
- Python String Method – title()
- Python String Method – center()
- Python String Method – count()
- Python String Method – startswith()
- Python String Method – endswith()
- Python String Method – find()