Home  >  Article  >  Backend Development  >  What is the usage of index in python

What is the usage of index in python

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼Original
2019-07-23 10:48:2522875browse

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 "", line 1, in 
  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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Usage of len() in pythonNext article:Usage of len() in python