Python String index() Method
The index() method checks if the string contains the substring str, and if the beg and end ranges are specified, checks if it is contained within the specified range.
Python String index() Syntax
The index() method syntax.
str.index(str, beg=0, end=len(string))
Python String index() Parameters
- str – the string to be retrieved
- beg – Start index, default is 0.
- end – the end index, defaults to the length of the string.
Python String index() Return Value
Returns the starting index if the string contains substrings, otherwise throws an exception.
Python String index() Example#1
The following example shows an instance of the index() method.
#!/usr/bin/python3
str1 = "apidemos example....wow!!!"
str2 = "exam";
print (str1.index(str2)) # Basic usage of Python String index() Method
print (str1.index(str2, 5)) # Python String index() With start and end Arguments
print (str1.index(str2, 10)) # Exception when using Python String index() Method
Output: