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

What is the usage of index in python

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

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(&#39;a&#39;)
ValueError: tuple.index(x): x not in tuple
>>> t.index(&#39;e&#39;)
3
>>> t.index(&#39;l&#39;)
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(&#39;l&#39;,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