The index Method in Python: Finding the Index of a Substring in a String
Returns the smallest index where the specified substring is found in the original string.
index(sub[, start[, end]])
sub-- substring whose starting index must be determinedstart=0-- starting index of the slice in the original string where the substring must be foundend=None-- ending index of the slice in the original string where the substring must be found
This method works like str.find(), but raises an exception if the substring is not found.
my_str = 'barbarian'
my_str.index('bar') # 0
my_str.index('bar', 1) # 3
my_str.index('bar', 1, 2) # ValueError
The optional parameters start and end can take any values supported by slicing, including negative values.
Use this method only when you need the starting index of a substring. To check if a substring is present, use the in operator:
my_str = 'barbarian'
if 'bar' in my_str: ... # True