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

What is the usage of index in python

爱喝马黛茶的安东尼
Release: 2019-07-23 10:48:25
Original
23074 people have browsed it

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
Copy after login

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))
Copy after login

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
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template