Python String index() method
Python String index() method
The string.index() method in Python finds the lower index of the first occurrence of the specified value or raise a ValueError if the substring is not found.
Syntax
index(sub[, start[, end]])
Parameter
sub: This parameter represents a substring which is to be searched in the given string.
start( Optional): This parameter signifies the substring from where the search is to start and its default value is 0.
end: This parameter signifies the substring from where to end the search and its default value is the end of the string
Return
This method returns the lowest index in the string if the substring is found else it raises a ValueError exception if the specified substring doesn't exist inside the string.
Example 1
# Python programing explaining # the index() method # initializing the string strVal = "Hello everyon, welcome to my world." # passing the substring substring="welcome" # returning the lowest index in the string if the substring index = strVal.index(substring) # prinitng the index of the specified substring print("The index of '",substring,"' is",index)
Output
The index of ' welcome ' is 15
Example 2
# Python programing explaining # the index() method # initializing the string strVal = "Python language is easy to learn." # Substring is searched in 'gramming is fun.' print(strVal.index('guage', 10)) # Substring is searched in 'gramming is ' print(strVal.index('ge is', 7, 20)) # Substring is searched in 'programming' # will return a ValueError error as the Substring is not there between the start or end value print(strVal.index('easy', 7, 18))
Output
10 13 Traceback (most recent call last): File "main.py", line 14, in <module> print(strVal.index('easy', 7, 18)) ValueError: substring not found