Home > Article > Backend Development > What is the usage of index in python
index()
The general purpose is to retrieve parameters in a sequence and return the index of the first occurrence. If it is not found, an error will be reported, such as:
>>> t=tuple('Allen') >>> t ('A', 'l', 'l', 'e', 'n') >>> t.index('a') Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> t.index('a') ValueError: tuple.index(x): x not in tuple >>> t.index('e') 3 >>> t.index('l') 1
But the parameter may appear many times, how to do it?
Related recommendations: "Python Tutorial" The complete syntax of the
index() function is as follows:
str.index(str, beg=0, end=len(string))
str – specifies the string to be retrieved
beg – Starting index, default is 0.
end – end index, defaults to the length of the string.
So we can reset the starting index to continue searching, such as:
>>> t.index('l',2) 2
Because the first 'l' appears at 1, we will add 1 to the starting index to continue searching, and sure enough , and 'l' is found at index 2.
The above is the detailed content of What is the usage of index in python. For more information, please follow other related articles on the PHP Chinese website!